不使用class关键字扩展数组



是否可以在不使用class关键字的情况下扩展构建?据我所知,class关键字不仅仅是语法糖。但这个或类似的东西行得通吗?

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

当然。正如您所注意到的,javascript中的继承是在class关键字存在之前的事情。你的例子与你的做法非常接近。事实上,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();

最新更新