js several inheritance modes (traditional, call / apply, shared prototype, holy grail mode)



1Traditional model-prototype chain Father.prototype.name = "deng" function Father () { 
} var father = new Father ()
 var son = new Father () 
father.name // deng 
son.name // deng too much Inherited useless attributes. 
2. Borrow constructor call, apply function Person (name, age) {    this.name = name;    this.age = age; } var person = new Person ('zhangsan', 15); var obj1 = (} Person.call (obj1, 'wangmazi', 29) console.log (obj1) // {name: "wangmazi", age: 29}


















  Cannot inherit the prototype of the borrowed constructor

  Execute one more function

   3. Shared prototype

  function Father(){}

   function Son(){}

   Father.prototype.lastName = 'deng';
   Son.prototype = Father.prototype;

   var son = new Son ();

  son.lastName //'deng'

   You can't change your prototype randomly, because it points to the same space.

 4. Holy Grail Mode Add an intermediate layer based on the shared prototype

  

function Father(){}
function Son(){}
Father.prototype.lastName = 'qin';

var extend = (function(){
var Mid = function(){}
return function (Target, Origin){
Mid.prototype = Origin.prototype;
Target.prototype = new Mid();
Target.prototype.constructor = Target
}
}())

extend(Son, Father);
var son = new Son();

 

Son.prototype.firstName = "333" Adding attributes to Son's prototype does not affect Father's prototype

 

Guess you like

Origin www.cnblogs.com/h5it/p/12750107.html