Javascript 命名空间对象原型
我想用一些额外的方法来增强对象,例如将Javascript 命名空间对象原型,javascript,Javascript,我想用一些额外的方法来增强对象,例如将first()或second()方法添加到数组中,但要使用命名空间,以便以[1,2].item.second()的方式调用它,而不是[1,2].second()。我得到了如下代码,但我得到了未定义的 Array.prototype.item = { first: function () { return this[0]; }, second: function () { return this[1];
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
引用数组的项
属性,而不是数组本身,这就是为什么得到未定义的
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()
最简单的方法是通过将item
转换为方法来捕获正确的上下文,如下所示:
Array.prototype.item = function() {
var _this = this;
return {
first: function() {
return _this[0];
},
second: function() {
return _this[1];
}
};
};
然后:
根据您的更新,如果坚持原始属性语法,可以尝试以下操作:
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, 2].item.first(); // 1
[1, 2].item.second(); // 2