Implementation of JS inheritance

father:

// define an animal class
function Animal (name) {
  // Attributes
  this.name = name || 'Animal';
  // instance method
  this.sleep = function(){
    console.log(this.name + 'Sleeping!');
  }
}
// prototype method
Animal.prototype.eat = function(food) {
  console.log(this.name + 'eating:' + food);
};

  

1. Prototype chain inheritance

function Cat(){
}
Cat.prototype = new Animal();
Cat.prototype.name = 'cat';

  

2. Construct inheritance call

function Cat(name){
  Animal.call(this);
  this.name = name || 'Tom';
}

  

5. Compositional Inheritance

function Cat(name){
  Animal.call(this);
  this.name = name || 'Tom';
}
Cat.prototype = new Animal();

6 Parasitic Combination Inheritance

function Cat(name){
  Animal.call(this);
  this.name = name || 'Tom';
}
(function(){
  // create a class with no instance methods
  var Super = function () {};
  Super.prototype = Animal.prototype;
  // use the instance as the prototype of the subclass
  Cat.prototype = new Super();
})();

  

3. Instance inheritance 

var instance = new Animal();
function Cat(name){
  var instance = new Animal();
  instance.name = name || 'Tom';
  return instance;
}

  

 

4. Copy inheritance

var instance = new Animal();再遍历复制
function Cat(name){
  var animal = new Animal ();
  for(var p in animal){
    Cat.prototype[p] = animal[p];
  }
  Cat.prototype.name = name || 'Tom';
}

  




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324931433&siteId=291194637