我正在使用Babel通过内置的本机Array扩展我的课程class NewArray extends Array { first() { return this[0]; }}var a = new NewArray(1, 2, 3);console.log(a.length); // 3console.log(a); // [ 1, 2, 3 ]console.log(a.first()); // trigger error在a.first()中,出现此错误:console.log(a.first()); ^ TypeError: a.first is not a function我是否应该做更多的事情来扩展内置的本机?谢谢!
3 回答

千巷猫影
TA贡献1829条经验 获得超7个赞
尽管我不明白为什么会收到错误(我无法重现此错误),但是您不会从first()函数中获得想要的结果。
您可以执行以下操作:
class NewArray extends Array {
constructor(){
super();
this.first = function(){ return this[0]; }
}
}
var a = new NewArray();
a.push(10);
console.log(a.first()); // 10
添加回答
举报
0/150
提交
取消