sách gpt4 ai đã đi

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

In lại 作者:搜寻专家 更新时间:2023-11-01 05:29:54 29 4
mua khóa gpt4 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'有没有办法为新分配的函数赋值?

1 Câu trả lời

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;

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

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

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

y;

still points to the same function() that logs 1


如果你想让 x 的改变影响 ,你应该做的是改变他们指向的东西,而不是改变它们指向什么.

Ví dụ:

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/

29 4 0
Bài viết được đề xuất: javascript - 函数不会在分离函数中触发
Bài viết được đề xuất: javascript - 使用 ng-click 更改出厂值
Bài viết được đề xuất: Javascript - 添加事件监听器时未定义的数组元素
Bài viết được đề xuất: javascript - Ember,如何从自定义适配器继承
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com