javascript传递对象作为参考 [英] javascript pass object as reference

查看:185
本文介绍了javascript传递对象作为参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,它在函数内的许多不同函数中传递。这些函数可能会也可能不会更改对象的值,但如果它们确实更改了它,那么我想获得对象的最新更改。

i have a object, which is getting passed in many different functions inside a function. these functions may or may not change the value of the object, but if they do change it, then i would like to get the latest changes on object.

以下是什么即时尝试:

var ob = {text: 'this is me', name: 'john'}

function (object) {

     changeObject(object);
     customObjectChanger(object);
     callback = function (object) {
          object.text = 'new text';
     }

     callback(object);

     // object value here should be object{text: 'new text', name: 'john'};    
}


推荐答案

在JavaScript中总是传递对象通过复制参考。我不确定这是否是完全正确的术语,但是会传入对象引用的副本。

In JavaScript objects are always passed by copy-reference. I'm not sure if that's the exactly correct terminology, but a copy of the reference to the object will be passed in.

这意味着对对象所做的任何更改在函数执行完毕后,您将可以看到。

This means that any changes made to the object will be visible to you after the function is done executing.

代码:

var obj = {
  a: "hello"
};

function modify(o) {
  o.a += " world";
}

modify(obj);
console.log(obj.a); //prints "hello world"

话虽如此,因为它只是副本的传入的引用,如果你重新分配函数内部的对象,这将 not 在函数外部可见,因为它只是副本您更改的引用。

Having said that, since it's only a copy of the reference that's passed in, if you re-assign the object inside of your function, this will not be visible outside of the function since it was only a copy of the reference you changed.

代码:

var obj = {
  a: "hello"
};

function modify(o) {
  o = {
    a: "hello world"
  };
}

modify(obj);
console.log(obj.a); //prints just "hello"

这篇关于javascript传递对象作为参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆