简体   繁体   English

javascript传递对象作为参考

[英]javascript pass object as reference

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.这些函数可能会也可能不会改变对象的值,但如果它们确实改变了它,那么我想获得对象的最新更改。

following is what im trying to do:以下是我想要做的:

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'};    
}

In JavaScript objects are always passed by copy-reference. 在JavaScript中,对象始终通过复制引用传递。 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. 这意味着在完成函数执行后,您可以看到对该对象所做的任何更改。

Code: 码:

 var obj = { a: "hello" }; function modify(o) { oa += " world"; } modify(obj); console.log(obj.a); //prints "hello world" 


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. 话虽如此,因为它只是传入的引用的副本 ,如果您在函数内部重新分配对象,这将在函数外部可见,因为它只是您更改的引用的副本

Code: 码:

 var obj = { a: "hello" }; function modify(o) { o = { a: "hello world" }; } modify(obj); console.log(obj.a); //prints just "hello" 

"Objects" are not values in JavaScript, and cannot be "passed". “对象”不是JavaScript中的值,也不能“传递”。

All the values that you are dealing with are references (pointers to objects). 您正在处理的所有值都是引用(指向对象的指针)。

Passing or assigning a reference gives another reference that points to the same object. 传递或分配引用会给出另一个指向同一对象的引用。 Of course you can modify the same object through that other reference. 当然,您可以通过其他引用修改同一个对象。

This is more explanation for Pass by value and Pass by reference (Javascript). 这是Pass by值和Pass by reference(Javascript)的更多解释。 In this concept, they are talking about passing the variable by reference and passing the variable by reference. 在这个概念中,他们讨论的是通过引用传递变量并通过引用传递变量。

Pass by value (Primitive Type) 通过价值(原始类型)

var a = 3;
var b = a;

console.log(a); // a = 3
console.log(b); // b = 3

a=4;
console.log(a); // a = 4
console.log(b); // b = 3
  • applies to all primitive type in JS(string, number, boolean, undefined, null). 适用于JS中的所有基本类型(字符串,数字,布尔值,未定义,null)。
  • a is allocated a memory (say 0x001) and b creates a copy of the value in memory (say 0x002). a分配一个内存(比如0x001), b在内存中创建一个值的副本 (比如0x002)。
  • So changing the value of a variable doesn't affect the other, as they both resides in two different locations. 因此,更改变量的值不会影响另一个变量,因为它们都位于两个不同的位置。

Pass by reference (objects) 通过引用传递(对象)

var c = { "name" : "john" };    
var d = c;

console.log(c); // { "name" : "john" }
console.log(d); // { "name" : "john" }

c.name = "doe"; 

console.log(c); // { "name" : "doe" }    
console.log(d); // { "name" : "doe" }
  • JS engine assigns the object to the variable c , it points to some memory say (0x012) JS引擎将对象分配给变量c ,它指向一些内存说(0x012)
  • when d=c , in this step d points to the same location (0x012). d=c ,在该步骤中d指向相同的位置(0x012)。
  • changing the value of any changes value for both the variable. 更改变量的任何更改值的值。
  • functions are objects 功能是对象

Special case, Pass by reference (objects) 特殊情况,通过引用(对象)

c = {"name" : "jane"}; 
console.log(c); // { "name" : "jane" }    
console.log(d); // { "name" : "doe" }
  • The equal( = ) operator sets up new memory space or address equal( = )运算符设置新的内存空间或地址

Basically, In JavaScript, there is no concept of Pass-By-Reference because Pass-by-value serves the purpose which makes JS so special.基本上,在 JavaScript 中,没有传递引用的概念,因为传递值服务于使 JS 如此特殊的目的。 when we pass an object in JavaScript, 1)function needs to with the value and that value is the reference copy 2)This value to the address of the original object.当我们在 JavaScript 中传递一个对象时,1) 函数需要使用该值,该值是引用副本2) 该值到原始对象的地址。

How can I handle this problem?我该如何处理这个问题? What if I want to change the object itself rather than its copy reference?如果我想更改对象本身而不是它的副本引用怎么办?

I wanted to reassign an object within a function and its new value be visible in the calling function.我想在函数中重新分配一个对象,并且它的新值在调用函数中可见。

To add to the great accepted answer, and address unanswered questions in comments there, here's my take on passing by reference with a look at scope / closure in practice:为了增加已被广泛接受的答案,并在那里的评论中解决未回答的问题,这是我对通过引用传递的看法,并在实践中查看范围/闭包

 const obj = { count: 0, } function incrementReference(_obj) { obj.count++ } function createIncrementByCopy(_obj) { let inner = {} Object.assign(inner, _obj) return function increment() { inner.count++ } } function createScopedIncrement(_obj) { return function increment() { _obj.count++ } } function createExtend(_obj) { return function increment(ext) { Object.assign(_obj, ext) } } console.log('obj', obj) // { count: 0 } incrementReference(obj) console.log('incrementReference ✅', obj.count) // 1 const incrementCopy = createIncrementByCopy(obj) incrementCopy() console.log('incrementCopy ❌', obj.count) // 1 const incrementA = createScopedIncrement(obj) incrementA() console.log('incrementA ✅', obj.count) // 2 const extendObj = createExtend(obj) extendObj({ text: 'New Property!' }) console.log('extendObj ✅', obj) // { count: 2, text: 'New Property!' }

Highly relevant: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#copying_accessors高度相关: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#copying_accessors

The following article discusses a common confusion about the terminology, which I really can't speak to 😆 https://dev.to/bytebodger/a-gotcha-of-javascript-s-pass-by-reference-1afm下面的文章讨论了一个关于术语的常见混淆,我真的不能说😆 https://dev.to/bytebodger/a-gotcha-of-javascript-s-pass-by-reference-1afm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM