js中的函数通过值或引用复制/传递

Ada*_*ady 4 javascript

我知道Javascript中的对象是通过引用复制/传递的.但功能怎么样?

当我跳到令人困惑的东西时,我正在尝试这段代码.这是代码片段:

x = function() { console.log('hey 1'); }

y = x;

x = function() { console.log('hey 2'); }

y; // Prints function() { console.log('hey 1'); }
Run Code Online (Sandbox Code Playgroud)

如果通过引用复制/传递像对象这样的函数,为什么y不会更新以打印'hey 2'?

如果这种行为是因为'x'被赋予了一个全新的函数,当x改变时,有没有办法将变量'y'变换为新分配的函数?

nem*_*035 5

JS中的所有内容都是按值传递的,其中对象和函数的值是引用.

这里发生的事情与对象相同(因为函数只是第一类对象):

这是正在发生的事情的要点:

x = function() { console.log('hey 1'); }
Run Code Online (Sandbox Code Playgroud)

x指向function() that logs 1(为此功能创建内存)

y = x;
Run Code Online (Sandbox Code Playgroud)

y指向function() that logs 1(相同的内存位置)

x = function() { console.log('hey 2'); }
Run Code Online (Sandbox Code Playgroud)

x现在指向一个新的 function() that logs 2(一个新的内存空间),y但没有任何影响

y;
Run Code Online (Sandbox Code Playgroud)

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'
Run Code Online (Sandbox Code Playgroud)