2013-07-06 49 views
2

我正在試圖圍繞這個'爭論傳遞'的想法。在我讀的一本書中,它指出參數只是通過值而不是參考來傳遞。在JavaScript中,這個參數是如何通過值傳遞而不是通過引用傳遞的?

function addTen(num) { 
    num + = 10; 
    return num; 
} 


var count = 20; 
var result = addTen(count); 
alert(count); // 20 - no change 
alert(result); // 30 

上面的例子很清楚,但下面的例子讓我非常困惑。

當人傳遞給setName函數時,是不是鏡像局部變量'obj' 並向下傳遞函數中的語句? 即人首先被設置爲屬性名稱,然後將其分配給新的對象,並且最後爲這個新創建的人物對象分配屬性'Gregg'?

爲什麼你得到'尼古拉斯'!!!!

function setName(obj) { 
    obj.name = "Nicholas"; 
    obj = new Object(); 
    obj.name = "Greg"; 
}   

var person = new Object(); 
setName(person); 
alert(person.name); //" Nicholas" 
+0

請找你的答案在這裏 - http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-參考或通過價值語言 – abipc

回答

2

將對象傳遞爲參考副本。現在發生的事情在你的例子是下一個:

var person = new Object();  

function setName(obj) { // a local obj* is created, it contains a copy of the reference to the original person object 
    obj.name = "Nicholas"; // creates a new property to the original obj, since obj here has a reference to the original obj 
    obj = new Object(); // assigns a new object to the local obj, obj is not referring to the original obj anymore 
    obj.name = "Greg"; // creates a new property to the local obj 
} 

setName(person); 
alert(person.name); //" Nicholas" 

* = obj是包含,這是原來的obj一參一局部變量。當您以後更改本地變量時,它不會反映到原始對象。

2

您得到"Nicholas"恰恰是因爲JavaScript永遠不被「引用」。如果是這樣,您可以從任何位置更新person變量。情況並非如此,因此函數中的new Object()不會改變外部變量person

但也不是變量引用對象本身,而是變量包含一種特殊類型的引用,可讓您在不直接訪問內存的情況下更新對象。

這就是爲什麼JavaScript總是「按價值」的原因,您永遠不會得到對象的完整副本。你只是得到一個特別參考的副本。因此,您可以操縱通過引用副本傳遞的原始對象,但實際上無法通過引用來替換它。

0

通過引用傳遞裝置這樣的:

function a(obj) { 
    obj = 3; 
} 

var test = new Object(); 
a(test); 
console.log(test); //3, so I have lost the object forever 

I.E.即使變量分配對調用者也是可見的。

當然,如果目標函數修改傳遞給它然後對象這些修改 對象本身將是給呼叫者可見。

2

在JavaScript中,所有東西都是按值傳遞的。當你將任何東西作爲參數傳遞時,JS會複製它並將其發送給函數。當Object傳遞時,JS將該對象的引用複製到另一個變量中,並將該複製的變量傳遞給該函數。現在,由於傳遞的變量仍然指向該對象,因此可以使用該變量來更改其屬性。或[]符號。但是如果你使用new來定義一個新對象,那麼該變量只是指向新的引用。

function setName(obj) { 
    obj.name = "Nicholas"; // obj pointing to person reference 
    obj = new Object(); // obj now pointing to another reference 
    obj.name = "Greg"; // you have changed the new reference not person reference 
}   

var person = new Object(); // person pointing to person reference 
setName(person); 
alert(person.name); //" Nicholas" 
+0

親愛的上帝,謝謝你的解釋和評論。當他們一起閱讀時,IT MADE非常有意義! –

1

參數通過值傳遞,而對於對象則表示該值是對該對象的引用的副本。

這是同樣的事情,當你做一個簡單的賦值,因爲,這也是通過值:

// a variable that contains a reference to an object: 
var person = new Object(); 
// another variable, that gets a reference to the same object: 
var people = person; 
// a function call with a reference to the object: 
setName(person); 

在功能方面,該參數是獨立運行,用於發送參考變量的局部變量進入功能,但它引用相同的對象:

function setName(obj) { 
    // as the variable references the original object, it changes the object: 
    obj.name = "Nicholas"; 
    // now the variable gets a reference to a new object 
    obj = new Object(); 
    // the new object is changed 
    obj.name = "Greg"; 
} 
相關問題