[英]JavaScript Set Prototype to Object
I'm trying to get the following code to work. 我正在尝试使以下代码起作用。
Array.prototype.test = {
func: function() {
console.log(this);
return this;
}
};
Then when I run the following. 然后,当我运行以下命令。
[].test.func();
The problem is the this
within that function is the object Array.prototype.test
NOT the array that I passed in. 问题是
this
该函数内是对象Array.prototype.test
NOT我在通过阵列。
I feel like there has to be way to do this without setting Array.prototype.test
to a function and having to call it like so [].test().func();
我觉得必须有一种方法,而不必将
Array.prototype.test
设置为一个函数,并且必须像[].test().func();
这样调用它[].test().func();
. 。
Chai uses this type of syntax quite a bit. Chai大量使用了这种语法。 So I'm assuming it's possible.
所以我认为这是可能的。
How can I get this to work as I'm expecting it to? 我如何才能像预期的那样工作?
JavaSript doesn't really have a good way to access that. JavaSript确实不是访问它的好方法。
You could use a getter for test
that returns a function with bound methods. 您可以使用吸气剂进行
test
,以返回带有绑定方法的函数。
Object.defineProperty(Array.prototype, 'test', { configurable: true, enumerable: false, get: function() { return { func: function() { console.log(this); return this; }.bind(this) }; } }); [].test.func();
But it's pretty convoluted compared to just using .testFunc
. 但是与仅使用
.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();
See How does the expect().to.be.true work in Chai? 请参阅Expect()。to.be.true在Chai中如何工作? to see they do roughly the same thing.
看到他们做大致相同的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.