JS中的一切都是按值傳遞其中對象和函數的值是引用。
這裏發生的事情是將與對象發生(因爲函數只是first-class objects)同樣的事情:
這裏是發生了什麼事情的要點:
x = function() { console.log('hey 1'); }
x
點function() that logs 1
(爲此功能創建內存)
y = x;
y
點function() that logs 1
(相同的內存位置)
x = function() { console.log('hey 2'); }
x
現在指向一個新function() that logs 2
(一個新的內存空間),沒有什麼影響y
雖然
y;
y
仍指向同一function() that logs 1
如果你想有改變x
影響y
,你應該做的是改變他們指向的事情,不能改變什麼他們指向。
例如:
var pointingAtMe = { log: function() { console.log('1'); } }
var x = pointingAtMe;
var y = pointingAtMe;
// change the actual thing x and y are both pointing to
x.log = function() { console.log('2'); } // this line also sets `y.log` and `pointingAtMe.log`since they all point to the same thing
// and the change gets applied to both
y.log(); // logs '2'
如果你使用'{x:1}'和'{x:2}'而不是'function(){console.log('hey 1'),那麼這種行爲是相同的。 }'和'function(){console.log('hey 2'); }'。你目前的措辭使得它聽起來像你正在觀察對象與功能的不同模式,但事實並非如此。 – apsillers
我幾乎在所有的編程語言中都發現一個常量,''='操作符只會修改它引用的變量(如實際引用「x」)而不是基礎數據。如果一個類型具有'.modify()'或'.add()'方法,那麼這是底層數據可以更改以便通過多個變量可見的一種方式。 – Katana314
對不起 - 自我警告:在JavaScript中,'='用於修改對象的屬性,當然可以被其他引用看到。例如:'var b = a; a.myprop = 3; console.log(b.myprop);' – Katana314