The prototype
property is defined on the function object itself, not the instance.
You could technically update the Array.prototype
with you max
function but then all Arrays in the current frame (past and present) will have the 'max' method. It is frowned upon to modify the prototype of native classes if you expect to work alongside 3rd party JavaScript. If you would like to inherit from the native Array
class, you can use the simple inherits
function listed below and call the parent class constructor. For a more detailed explanation on why this method of inheritance is preferred over others, please check out this post on how the inherits function works
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