简体   繁体   English

TypeError:this.list.push不是ecmascript 6中的函数

[英]TypeError: this.list.push is not a function in ecmascript 6

When calling the add function of my GroceryList class, I get an error: 调用GroceryList类的add函数时,出现错误:

TypeError: this.list.push is not a function TypeError:this.list.push不是函数

Why is this? 为什么是这样?

class GroceryList {

      constructor() {
        this.list = {
            value: [],
            writable: false,
            enumerable: true  
          };
      }

        add(item) {
        this.list.push(item);
      }

      getAll() {
        return this.list;
      }

      getItemIndex(value) {
        var index = this.list.length;
        while(--index > -1) {
          if(this.list[index] === value) {
            return index;
          }
        }
        return -1;
      }
    }

You are confusing 你很困惑

  • A whole object 整个对象

vs VS

  • A list as an attribute of that object 列表作为该对象的属性

The list object contains a list, but that does not mean it is a list. list对象包含一个列表,但这并不意味着它是一个列表。 You should write list.value.push(x) 您应该编写list.value.push(x)

It seems you are trying to use a property descriptor . 看来您正在尝试使用属性描述符 However, those descriptors only work with Object.defineProperty . 但是,这些描述符仅与Object.defineProperty一起Object.defineProperty

this.list = {
  value: [],
  writable: false,
  enumerable: true  
};

literally assigns an object with the properties value , writable and enumerable to this.list . 字面上分配与所述属性的对象valuewritableenumerablethis.list

What you seem to want is: 您似乎想要的是:

Object.definProperty(this, 'list', {
  value: [],
  writable: false,
  enumerable: true  
});

Now this.list returns an array, but it's not possible to assign a new value to the property. 现在this.list返回一个数组,但是无法为该属性分配新值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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