该prototype
属性是在函数对象本身上定义的,而不是在实例上。您可以在技术上更新Array.prototype
with youmax
函数,但是当前帧(过去和现在)中的所有数组都将具有“max”方法。如果您希望与 3rd 方 JavaScript 一起工作,那么修改原生类的原型是不受欢迎的。如果您想从原生Array
类继承,可以使用inherits
下面列出的简单函数并调用父类构造函数。有关为什么这种继承方法比其他方法更受欢迎的更详细解释,请查看这篇关于继承函数如何工作的帖子
function inherits(childConstructor, parentConstructor){
var TempConstructor = function(){};
TempConstructor.prototype = parentConstructor.prototype; // Inherit parent prototype chain
childConstructor.prototype = new TempConstructor(); // Create buffer object to prevent assignments directly to parent prototype reference.
childConstructor.prototype.constructor = childConstructor; // Reset the constructor property back the the child constructor (currently set to TempConstructor )
};
var CustomArray = function(){
// Normally the below line would suffice, but the native Array class is overloaded in that a cast (or call) returns a new array instance.
//Array.apply(this, arguments);
this.push.apply(this, arguments); // This will achive what we originally wanted from `Array.apply(this, arguments);`
}
inherits(CustomArray, Array);
CustomArray.prototype.max = function(){
var length = this.length;
if(!length){
return;
}
var maxValue = this[0];
for(var i = 1; i < length; ++i){
var value = this[i];
if(value > maxValue){
maxValue = value;
}
}
return maxValue;
}
var nativeArray0 = new Array();
var nativeArray1 = new Array(1, 3, 4, 9, 5, 0, 7, 11, 2);
var customArray0 = new CustomArray();
var customArray1 = new CustomArray('c', 'a', 'd', 'b', 'f', 'y', 'g', 'p');
alert('customArray0.max() = ' + customArray0.max()); // undefined
alert('customArray1.max() = ' + customArray1.max()); // y
alert('CustomArray.prototype.max.call(nativeArray1) = ' + CustomArray.prototype.max.call(nativeArray1)); // 11
alert('nativeArray0.length = ' + nativeArray0.length); // 0
alert('nativeArray1.length = ' + nativeArray1.length); // 9
alert('nativeArray1[3] = ' + nativeArray1[3]); // 9
alert('customArray0.length = ' + customArray0.length); // 0
alert('customArray1.length = ' + customArray1.length); // 8
alert('customArray1[3] = ' + customArray1[3]); // b