JavaScript 类与数组功能的增强
1. 内置对象的继承
在 JavaScript 中,开发者一直希望通过继承创建自己的特殊数组类型。在 ECMAScript 5 及更早版本中,使用经典继承无法实现这一功能。例如:
// 内置数组行为
var colors = [];
colors[0] = "red";
console.log(colors.length); // 1
colors.length = 0;
console.log(colors[0]); // undefined
// 在 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"
上述代码表明,使用经典继承会导致意外行为, My
超级会员免费看
订阅专栏 解锁全文
24

被折叠的 条评论
为什么被折叠?



