functionAnimal(){} Animal.prototype.eat = function(){console.log('I can eat');}; //给Animal的原型添加eat方法
functionHuman(){} Human.prototype = newAnimal(); //这行代码可以拆成两行理解, //var animal = new Animal; 此时animal.__proto__引用自Animal.prototype,既animal.__proto__.hasOwnPropety('eat')返回true //Human.prototype = animal; 此时Human.prototype.__proto__.hasOwnPropety('eat')返回true //则有 Human.prototype.__proto__.eat(); 打印 I can eat //而JS中可以省略__proto__直接用"."去访问__proto__上的属性,所以这时候可以像这样调用eat方法: //Human.prototype.eat(); 打印 I can eat
//所以应该可以理解下面的代码了: //var someone = new Human(); //上面的new构造过程包括了这样的操作: someone.__proto__ = Human.prototype; //既someone.__proto__ = animal; //则有: //someone.__proto__.__proto__.eat(); 打印 I can eat。 //省略__proto__后 //someone.eat(); I can eat //既someone对象继承了Animal上的eat方法。
Human.prototype.speak = function(){console.log('I can speak');}; //此时Human.prototype这个由Animal构造的对象拥有了speak方法
functionCoder(){} Coder.prototype = newHuman(); Coder.prototype.coding = function(){console.log('I can coding');};
functionJSer(){} JSer.prototype = newCoder(); JSer.prototype.codingInJS = function(){console.log('I can conding in JS');};
//以下调用均省略了__proto__属性 console.log(me.eat()); //打印I can eat 。eat继承自构造函数Animal console.log(me.speak()); //打印I can speak。speak方法继承自构造函数Human console.log(me.coding()); //打印I can coding。 coding方法继承自构造函数Coder console.log(me.codingInJS()); //打印I can coding in JS。 codingInJS方法继承自构造函数JSer