不使用class关键字扩展数组

时间:2018-11-02 16:59:09

标签: javascript

是否可以在不使用class关键字的情况下扩展buildins? 据我了解,class关键字不仅仅是语法糖。但这会起作用吗?

MyArray = function () {}
MyArray.prototype = Object.create(Array.prototype)

1 个答案:

答案 0 :(得分:4)

当然。您注意到,在JavaScript中继承是class关键字存在之前的事情。您的示例非常接近如何执行此操作。实际上,the documentation for Object.create给出了一个示例,该示例说明了如何无需使用class就可以实现继承。

要将他们的示例应用于您的示例,您可以这样做:

const MyArray = function() {
  Array.call(this); // Call parent constructor
}

MyArray.prototype = Object.create(Array.prototype);
MyArray.prototype.constructor = MyArray; // Set constructor

// Add methods:
MyArray.prototype.test = function() {
  this.forEach(element => console.log("Element:", element));
}

// Now you can create new MyArray's that inherit from Array:

const myArray = new MyArray();

myArray.push("hello");
myArray.push("world");
myArray.test();

相关问题