我想使用一些额外的方法来增强对象,例如向数组添加 first()
或 second()
方法,但使用命名空间,以便它以 [1, 2].item.second()
方式调用,而不是 [1, 2].second()
。我得到如下代码,但我得到未定义
。
Array.prototype.item = {
first: function () {
return this[0];
},
second: function () {
return this[1];
}
};
[1, 2].item.second()
// undefined
// I don't want to use [1, 2].second()
最佳答案
first()
和 second()
函数中的 this
引用了 item
属性数组,而不是数组本身,这就是为什么你会得到未定义
。
最简单的方法是将 item
转换为方法来捕获正确的上下文,如下所示:
Array.prototype.item = function() {
var _this = this;
return {
first: function() {
return _this[0];
},
second: function() {
return _this[1];
}
};
};
然后:
[1, 2].item().first(); // 1
[1, 2].item().second(); // 2
根据您的更新,如果您坚持使用原始属性语法,您可以尝试以下操作:
Object.defineProperty(Array.prototype, 'item', {
get: function() {
var _this = this;
return {
first: function() {
return _this[0];
},
second: function() {
return _this[1];
}
};
}
});
然后:
[1, 2].item.first(); // 1
[1, 2].item.second(); // 2
参见MDN
关于javascript - 命名空间对象原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44995753/