簡體   English   中英

了解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本身進行了更改,但是當我嘗試通過將obj null傳遞給change_obj來使obj null ,它沒有更改obj。 也沒有change_obj_x了我的預期。

請對此進行解釋,並給我一些鏈接以了解有關函數的所有知識。

當您在類似in的函數中向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 (ie 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);

做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM