了解 JavaScript 中的函数

Understanding functions in javascript

本文关键字:函数 JavaScript 了解      更新时间:2023-09-26

我玩过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 本身进行了更改,但是当我尝试通过将其传递给 change_objobj null时,它并没有更改 obj。change_obj_x也没有达到我的预期。

请解释这一点,并给我一些链接来了解有关函数的所有信息。

当您在函数中分配某些内容以o

时,例如
function change_obj(o) { o = null; }

您无需更改参数,只需将null分配给变量即可。由于 o 变量在函数外部不存在,因此不会发生任何操作。

相比之下,

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

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

在函数function change_obj_x(o)中,将这两种效应结合起来。首先,更改 ox 属性(引用您的obj),然后将null分配给 o 。后者不影响obj.

查看函数

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

做。