了解 JavaScript 中的函数
Understanding functions in javascript
我玩过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_obj
来obj 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)
中,将这两种效应结合起来。首先,更改 o
的 x
属性(引用您的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);
做。
- 从函数JavaScript返回不可变数组/对象
- 将对象传递给函数.JavaScript
- 如何定义const函数javascript(语法糖)
- 新的日期函数javascript
- TypeError:this.getAttribute不是一个函数-javascript
- 从函数javascript发送变量
- 扩展自容器函数Javascript
- 从内部函数javascript内部分配外部函数的对象
- 使用函数JavaScript中的函数
- 在这里使用回调函数(JavaScript)有什么好处吗
- 来自函数 Javascript 的 NaN 返回值 ||函数执行顺序
- 将“e”传递给一个新函数 - javascript
- 调用函数中的一个函数——Javascript
- 传递的变量不适用于我的函数-Javascript
- 如何将类方法设置为等于多个函数?-Javascript
- 显示php中的函数javascript
- 如何使用php代码创建函数Javascript弹出框
- 未调用的外部函数-javascript
- 如何在类中运行函数.Javascript
- 关闭mouseover上的一个函数——Javascript,jQuery