有点远了。但是无论如何,是否可以在构造函数原型(prototype)上获取链接属性,并且仍然使“this”上下文指向原始对象实例。例如:
Array.prototype.$ = {};
Array.prototype.$.where = function(selector) {
console.log(this);
return;
};
var myArray = [ 1, 2, 3 ];
myArray.$.where();
控制台输出 { where: [Function] }
,'this' 上下文指向 where function $ 对象,而不是数组本身。
但是,如果我将其更改为:
Array.prototype.where = function(selector) {
console.log(this);
return;
};
var myArray = [ 1, 2, 3 ];
myArray.where();
它正确输出[ 1, 2, 3 ]
最佳答案
您函数中的
this
是 myArray.$
,它与 Array.prototype.$
完全相同。您可以执行 console.log(myArray.$)
或 console.log(Array.prototype.$)
,它们将打印与 myArray.$ 相同的结果。其中();
这是什么意思?当您调用 myArray.$.where();
时,您实际上是在执行 Array.prototype.$.where();
。所以它的 context(this
) 变成了 Array.prototype.$
,所以它不会像你预期的那样工作。
还有一件事:extending the DOM/built-in object prototype is generally considered harmful 。我强烈建议尝试另一种方式。
关于JavaScript - 原型(prototype)上具有正确 'this' 上下文的链接属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18013566/