我这里的继承内置对象功能无效

来源:3-14 类与对象

你江饱受折

2017-05-04

// 在 ES5 中尝试继承数组

function MyArray() {
    Array.apply(this, arguments);
}

MyArray.prototype = Object.create(Array.prototype, {
    constructor: {
        value: MyArray,
        writable: true,
        configurable: true,
        enumerable: true
    }
});

var colors = new MyArray();
colors[0] = "red";
console.log(colors.length);         // 0

colors.length = 0;
console.log(colors[0]);             // "red"


在 ES6 中就可以继承成功

class MyArray extends Array {
  // 空代码
}

var colors = new MyArray();
colorsp[0] = 'red';
console.log(colors.length);		// 1

colors.length = 0;
console.log(colors[0]);	            // undefined


第一种继承方式哪里出了问题,帮看一下.

写回答

1回答

快乐动起来呀

2017-05-06

其实第一种已经实现了继承,可以试试用对象push,pop等数组的方法操作,只是这种继承不能使用[]运算符操作

0
1
mylovef
为什么这里不能用[]操作呢
2017-05-06
共1条回复

ES6零基础教学 解析彩票项目

ES6从零开始,量身设计的迷你案例,让你全面掌握ES6

2579 学习 · 881 问题

查看课程