试想需要实现一个数组的子类ZeroArray,其构造函数接收一个长度参数n,自动初始化数组元素都为0。
我试图继承原生的Array类型,成员变量通过apply()方法窃取,成员方法则通过原型链引用。代码如下:
function ZeroArray(n) { // 构造函数窃取
Array.apply(this); // 自动塞入0元素
for (var i = 0; i < n; i++) { this.push(0);
}
}// 利用空函数作为过渡,ZeroArray原型的原型指向Array.prototype// 既建立原型链,又不影响Array.prototype本身,而且防止Array构造函数重复调用两次var F = function() {};
F.prototype = Array.prototype;
ZeroArray.prototype = new F();
ZeroArray.prototype.constructor = ZeroArray;那么问题来了:
Object.getOwnPropertyDescriptor(new Array(), "length")// 输出:Object {value: 0, writable: true, enumerable: false, configurable: false}
Object.getOwnPropertyDescriptor(new ZeroArray(3), "length")// 输出:Object {value: 3, writable: true, enumerable: true, configurable: true}为什么两者的length属性enumerable/configurable会不同?是不是因为Array本质上并不是Object?
炎炎设计
梵蒂冈之花
随时随地看视频慕课网APP
相关分类