简体   繁体   English

Javascript object 传入 function 但显然是按值传递

[英]Javascript object passed in a function but apparently passed by value

As javascript objects are passesd by reference then why console.log(obj1.a) is showing 1 instead of 7. As function is changing value to 7.由于 javascript 对象是通过引用传递的,那么为什么console.log(obj1.a)显示 1 而不是 7。由于 function 正在将值更改为 7。

 obj1 = { a: 1 } obj2 = { a: 1 } function c(d) { console.log('d bef ', typeof d) if (typeof d === 'object'){ d = obj2 obj2.a = 7 console.log ('d.a', da) } } c(obj1) console.log(obj1.a)

By passing the data as a parameter, you pass the object value but not the reference, So, you have a new object with a new reference, just scoped for the function.通过将数据作为参数传递,您传递的是 object 值而不是引用,因此,您有一个新的 object 和一个新的引用,仅适用于 function。

This is a simpler example.这是一个更简单的例子。

 // The pet variable have the referance of the { type: 'cat' } object. let pet = { type: 'cat' } // p is a copy of the pet variable but not have the same referance. const changeThePet = (p) => { p = { type: 'dog' } } // here you pass the pet variable changeThePet(pet) console.log(pet)

p will hold the value of the pet but they aren't the same variable or same referance p将保存pet的值,但它们不是相同的variable或相同的referance

You seem confused by two different concepts.您似乎对两个不同的概念感到困惑。

In JS, objects ARE passed by references, but variable are not.在 JS 中,对象是通过引用传递的,但变量不是。

What does it means is that:它的意思是:

//WHen you declare your VARIABLE, you assign it a REFERENCE to a new object :
const something = { property : 'foo' };

//Something now is a variable whose value is a REFERENCE to an object, not the object itself.

function success(obj){
    obj.property = 'bar';
}

function fail(obj){
    obj = { property : 'bar' }: 
}
//When you call fail : 

fail(something);
console.log(something.property); //will print foo

//When you call success : 

success(something);
console.log(something.property); //will print bar

In success function above, you access the object by reference through the function argument and you change its property.在上面的success function 中,您通过 function 参数通过引用访问 object 并更改其属性。 Because when you call success , the variable something pass its reference to the object by value .因为当您调用success时,变量something 通过将其引用传递给object。 So, the argument of success ( obj ) has for value the reference to the object.因此, success ( obj ) 的参数具有对 object 的引用价值

in fail , you replace the reference to the object by a reference to another object . fail ,则将 object 的引用替换为对另一个 object的引用。

To be clear: the something variable is passed by value .需要明确的是: something变量是通过value传递的。 But this value is a reference to an object.但这个值是对 object 的引用

Thus, you can change object properties through this reference, but you can't change the something variable value by assigning a new value to the function's parameter obj .因此,您可以通过此引用更改 object 属性,但不能通过为函数的参数obj分配新值来更改something变量值。

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

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