You can add prototype to any object in Jacascript likes Object, Array, String...
prototype 有继承的作用,比如说我有一个String的对象,我可以访问Object的prototype hasPrototype() function,
StrObj -- String --Object,
你每创建的一个StrObj, 它之所以可以使用.shift(), pop(), push() methods是应为那些methods都是String object继承下去的。
Array.prototype.countCattle = function ( kind ){ var numKind = 0; for(var i = 0; i<this.length; i++){ if(this[i].type == kind){ numKind++; } } return numKind; }; alert(canyonCows.countCattle("calf")+valleyCows.countCattle("bull")+forestCows.countCattle("cow"));
Object.prototype.noCalvesYet = function () { if(this.type == "cow" && this.hadCalf == null){ return true; } return false; }; Array.prototype.countForBreeding = function(){ var numToBreed = 0; for(var i = 0; i < this.length; i++){ if(this[i].noCalvesYet()){ numToBreed++; } } return numToBreed; };