2

我玩过javascript,就是这样:

> var obj = new Object();

> obj
{}
> obj.x = 0;
0
> function change_x(o) { o.x = o.x + 1; }

> change_x(obj);

> obj
{ x: 1 }
> function change_obj(o) { o = null; }

> change_obj(obj);

> obj
{ x: 1 }

function change_obj_x(o) { console.log(o); o.x = o.x + 1; o = null; console.log(o); }

> change_x(obj)

> change_obj_x(obj);
{ x: 2 }
null

> obj
{ x: 3 }

当我传递obj给 时change_x,它对 obj 本身进行了更改,但是当我尝试obj null通过将其传递给 时change_obj,它并没有更改 obj。也change_obj_x没有我所期望的。

请解释一下并给我一些链接以了解有关功能的所有信息。

4

2 回答 2

4

当您将某些内容分配给o诸如 in 之类的函数时

function change_obj(o) { o = null; }

您不更改参数,而只是分配null给变量。由于该o变量不存在于函数之外,因此什么也没有发生。

相比之下,

function change_x(o) { o.x = o.x + 1; }

改变参数本身。由于参数是通过引用传递的,所以x属性的值也在函数外部发生了变化。

在你的函数function change_obj_x(o)中,你结合了这两种效果。首先,您更改(引用您的)的x属性,然后分配给. 后者不影响。oobjnulloobj

于 2013-10-21T08:27:44.043 回答
1

功能

If you pass an object (i.e. a non-primitive value, such as Array or a user-defined object) as a parameter, and the function changes the object's properties, that change is visible outside the function

Note that assigning a new object to the parameter will not have any effect outside the function, because this is changing the value of the parameter rather than the value of one of the object's properties

有一个很好的解释:

Imagine your house is white and you give someone a copy of your address and say, "paint the house at this address pink." You will come home to a pink house.

这就是你所做的

> function change_x(o) { o.x = o.x + 1; }
> change_x(obj);


Imagine you give someone a copy of your address and you tell them, "Change this to 1400 Pennsylvania Ave, Washington, DC." Will you now reside in the White House? No. Changing a copy of your address in no way changes your residence.

就是这样

> function change_obj(o) { o = null; }
> change_obj(obj);

做。

于 2013-10-21T08:43:13.937 回答