简体   繁体   English

javascript对象属性作为参数

[英]javascript object properties as parameters

If in javascript object properties are passed by reference why this doesnt work: 如果在javascript对象属性中通过引用传递了,这为什么不起作用:

var myObj={a:1}

function myFun(x){
x=2;
}

myFun(myObj.a);

// value myObj.a is still 1

but on the other hand if you do this: 但另一方面,如果您这样做:

var myObj={a:1}

function myFun(x){
x.a=2;
}

myFun(myObj);

// this works myObj.a is 2

your first example doesn't work, because object properties are not passed by reference (unless the property itself also is an object). 您的第一个示例不起作用,因为对象属性不是通过引用传递的(除非属性本身也是一个对象)。

objects, as you noticed, are passed by reference - thats the reason your second example works. 正如您所注意到的,对象通过引用传递的-这就是第二个示例起作用的原因。

Primitive values are passed by value. 原始值按值传递。 Objects are passed by reference. 对象通过引用传递。

Object properties are passed by based on their data type. 对象属性根据其数据类型传递。

Here you are passing an integer - x represents the value 1. Assigning x the value 2 does not reference the original object. 在这里,您传递一个整数x表示值1。为x分配值2不会引用原始对象。

Let's say the property you pass in is an array. 假设您传入的属性是一个数组。 And the 2nd function I call receives an array and you make changes to that array. 我调用的第二个函数接收到一个数组,然后您对该数组进行更改。 Then the changes will persist to the object because the object's property contains a reference to the array you modified. 然后,更改将保留在对象上,因为对象的属性包含对您修改的数组的引用。 You didn't technically modify the object at all... you just modified the array which is referenced in the object. 从技术上讲,您根本没有修改对象……您只是修改了对象中引用的数组。 When you pass an object property to a function, it's not aware that it belongs to an object at all. 当您将对象属性传递给函数时,它根本不知道它属于对象。

See example, similar to yours: 查看示例,类似于您的示例:

var myObj={a:[1]}

function fn1(x){
 x=2; //Overwrites x in this scope to the new primitive 2. 
      //This isn't reflected in myObj because x is not a 
      //reference to myObj.a  it is a reference to the array 
      //that myObj.a contains (the [1]).
}

function fn2(x){
 x.push(2);
}

fn1(myObj.a); //myObj.a is [1]
fn2(myObj.a); //myObj.a is [1,2]

When you pass a base data type, it is passed by value. 传递基本数据类型时,将按值传递。 That is for integers, you pass the parameter by value so a copy of it is made in the local scope. 也就是说,对于整数,您按值传递参数,以便在本地范围内复制它。 Objects however are passed by reference so the function has access to the variable. 但是,对象是通过引用传递的,因此该函数可以访问该变量。 You could pass it by reference, but its easier to do 您可以通过参考传递它,但是它更容易实现

 Obj.a=fun(Obj.a);

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

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