簡體   English   中英

如何在javascript Object.defineProperty 中定義數組的getter 函數?

[英]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的元素並從myclasslist檢索它們。

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM