gpt4 book ai didi

JavaScript 将原型(prototype)设置为对象

转载 作者:行者123 更新时间:2023-11-30 09:24:55 24 4
gpt4 key购买 nike

我正在尝试让以下代码正常工作。

Array.prototype.test = {
func: function() {
console.log(this);
return this;
}
};

然后当我运行以下命令时。

[].test.func();

问题是该函数中的 this 是对象 Array.prototype.test 不是 我传入的数组。

我觉得必须有一种方法可以做到这一点,而无需将 Array.prototype.test 设置为函数,并且不必像这样调用它 [].test().func( );

Chai 经常使用这种语法。所以我假设这是可能的。

我怎样才能让它像我期望的那样工作?

最佳答案

JavaSript 并没有真正的访问它的好方法。

您可以为 test 使用一个 getter,它返回一个带有绑定(bind)方法的函数。

Object.defineProperty(Array.prototype, 'test', {
configurable: true,
enumerable: false,
get: function() {
return {
func: function() {
console.log(this);
return this;
}.bind(this)
};
}
});

[].test.func();

但与仅使用 .testFunc 相比,它相当复杂。

// Using Object.defineProperty to avoid enumerable prototype properties.
Object.defineProperty(Array.prototype, 'testFunc', {
configurable: true,
enumerable: false,
writable: true,
value: function() {
console.log(this);
return this;
}
});

[].testFunc();

参见 How does the expect().to.be.true work in Chai?看看他们做大致相同的事情。

关于JavaScript 将原型(prototype)设置为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49594447/

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