gpt4 book ai didi

具有硬绑定(bind)的新 Javascript

转载 作者:行者123 更新时间:2023-11-30 16:00:29 25 4
gpt4 key购买 nike

我有以下代码片段

function foo(a) {
this.a = a;
}

var obj = {a: 77};

var bar = function() {
return foo.apply( obj, arguments );
};

var o = new bar( 2 );

console.log( o.a ); // I think it's 2(why is it undefined?)
console.log(obj.a); // obj.a changed to 2, got it.

为什么 o.a 未定义?如果我删除 bar 中的 return 关键字,它仍然是一样的。

function foo(a) {
this.a = a;
}

var obj = {a: 77};

var bar = function() {
foo.apply( obj, arguments );
};

var o = new bar( 2 );

console.log( o.a ); // I think it's 2(why is it undefined?)
console.log(obj.a); // obj.a changed to 2, got it.

问题实际上是当硬绑定(bind)和新绑定(bind)同时发生时会发生什么

最佳答案

使用 new将创建一个新对象并将该对象作为 this 分配给您调用它的函数。在您的情况下,您没有使用新对象,而是调用函数设置 obj 作为 this

至于为什么添加和删除 return 不会改变任何东西,因为在这两种情况下,您都返回 undefined。当使用 new 调用函数并返回 undefined(也就是默认返回值)时,它会返回由 new 生成的新对象。

引用MDN :

The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)

因此,您创建了一个新对象,但操作了一个旧对象。您的代码实际上是这样工作的。

function foo(a) {
this.a = a;
}

var obj = {a: 77};

var bar = function() {
return foo.apply( obj, arguments );
};

var o = {}; // Originally you used `new` to create a new object
bar(2); // Since `bar` doesn't use `this`, it's the same as if it were called by itself

console.log(o.a); // Empty object
console.log(obj.a); // Modified by `bar`

关于具有硬绑定(bind)的新 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37841796/

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