gpt4 book ai didi

javascript - js中的函数按值或引用复制/传递

转载 作者:搜寻专家 更新时间:2023-11-01 05:29:54 26 4
gpt4 key购买 nike

我知道 Javascript 中的对象是通过引用复制/传递的。但是函数呢?

当我跳到一些令人困惑的地方时,我正在尝试这段代码。这是代码片段:

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

y = x;

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

y; // Prints function() { console.log('hey 1'); }

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

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

最佳答案

JS 中的一切都是按值传递,其中对象和函数的值是一个引用。

这里发生的事情与对象发生的事情相同(因为函数只是 first-class objects ):

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

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

x points to function() that logs 1 (memory is created for this function)

y = x;

y points to function() that logs 1 (same memory location)

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

x now points to a new function() that logs 2 ( a new memory space), nothing affected y though

y;

y still points to the same 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'

关于javascript - js中的函数按值或引用复制/传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33809015/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com