了解javascript中的函数

时间:2013-10-21 08:25:26

标签: javascript function

我玩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时,它没有改变了对象。 change_obj_x也达不到我的预期。

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

2 个答案:

答案 0 :(得分:4)

中的函数中为o分配内容时
function change_obj(o) { o = null; }

您不会更改参数,只需将null指定给变量即可。由于o变量在函数外部不存在,所以没有任何反应。

相比之下,

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

更改参数本身。当参数通过引用传递时,x属性的值也会在函数外部更改。

在你的函数function change_obj_x(o)中,你将这两种效果结合起来。首先,您更改x的{​​{1}}属性(引用您的o),然后将obj分配给null。后者不会影响o

答案 1 :(得分:1)

请参阅Functions

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);

做。