![](/img/trans.png)
[英]How to define getters and setters in javascript using object.defineproperty
[英]How to define the getter function of an array in javascript Object.defineProperty?
我希望我可以通過a.list
獲取列表,但是除了使用原始值返回之外,此代碼不起作用。
function myclass() {
this._v = {
list: []
};
}
Object.defineProperty(myclass.prototype, 'list', {
get: function() {
// return this._v.list;
return this._v.list.map(val => {
console.log('val', val);
return val;
});
}
});
var a = new myclass();
a.list.push('abc');
console.log(a.list);
getter 在調用時總是返回一個新的空數組。 當您推送到它時,沒有可觀察到的效果,因為正在更改的數組不是對象上的數組。 您需要獲得對_v.list
數組的引用,以便您可以推送到它,您可以通過直接引用它來完成
function myclass() { this._v = { list: [] }; } Object.defineProperty(myclass.prototype, 'list', { get: function() { return this._v.list.map(val => { return val; }); } }); var a = new myclass(); a._v.list.push('abc'); console.log(a.list);
或者添加一個不同的方法來返回_v.list
數組:
function myclass() { this._v = { list: [] } } myclass.prototype.getArr = function() { return this._v.list; } Object.defineProperty(myclass.prototype, 'list', { get: function() { return this._v.list.map(val => { return val; }); } }); var a = new myclass(); a.getArr().push('abc'); console.log(a.list);
也許您想推送_v.list
的元素並從myclass
新list
檢索它們。
function myclass() { this._v = { list: [] }; } Object.defineProperty(myclass.prototype, 'list', { get: function() { // return this._v.list; return this._v.list.map(val => { return val; }) } }); var a = new myclass(); a._v.list.push('abc'); console.log(a.list)
在您的代碼中,您已經覆蓋了list
get
方法,該方法從_v.list
獲取其所有元素,但是在將元素推送到list
您並沒有將它們推送到_v.list
。 這就是為什么你得到的是_v.list
而不是list
空數組。
'use strict';
function myclass() {
this._v = {
list: []
};
}
Object.defineProperty(myclass.prototype, 'list', {
get: function() {
// return this._v.list;
console.log('list', this._v.list);
return this._v.list.map(val => {
return val;
});
},
set: function(newVal) {
this._v.list.push(newVal);
}
});
const a = new myclass();
console.log(a);
a.list = 'abc';
console.log(a.list);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.