简体   繁体   中英

How to define the getter function of an array in javascript Object.defineProperty?

I expect that I can get the list by the a.list , but this code does not work except using original value return.

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);

The getter is always returning a new empty array when called. When you push to it, there are no observable effects, because the array that's being changed isn't the array on the object. You need to get a reference to the _v.list array so that you can push to it, which you can do either by reference it directly

 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);

Or add a different method that returns the _v.list array:

 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);

Maybe you wanted to push the elements in the _v.list and retrieve them from new list on myclass .

 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)

In your code you have overridden get method for list which is taking all its elements from _v.list but while pushing elements to list you are not pushing them to _v.list . That's why you are getting empty array which is _v.list not 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM