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