learning javascript - 继承

继承

call实现继承

用于实现函数继承,call的第二个参数能够是任意类型es6

function Animal(){
    this.name = "";
    this.say = function(){
        console.log("hello");
    }
}

function dog(){
    this.name = "xiao";
    //把Animal的方法应用到dog这个对象身上
    Animal.call(this);
}

console.log(new dog()); // dog { name: '', say: [Function] }

apply实现继承

用于实现函数继承,apply的第二个参数必须是数组,也能够是arguments数组

function Animal(){
    this.name = "";
    this.say = function(){
        console.log("hello");
    }
}

function dog(){
    this.name = "xiao";
    //把Animal的方法应用到dog这个对象身上
    Animal.apply(this,arguments);
}

console.log(new dog()); // dog { name: '', say: [Function] }

继承的优化

若是构造函数this绑定太多属性,在实例化后会形成浪费,为此咱们通常会使用原型链来优化,可是使用原型链以后咱们的apply和call的继承方法就会失效,所以咱们通常使用混合的写法。app

让子的原型链指向父的实例(父实例化的对象)
dog.prototype = new Animal();函数

让父的属性建立在子的this上
Animal.call(this)优化

function Animal(name){
    this.name = name;
    this.say = function(){
        console.log("hello");
    }
}
Animal.prototype.action = function() {
     console.log("running");
}
function dog(name,type){
    this.name = name;
    //把Animal的方法应用到dog这个对象身上
    Animal.call(this,type);
}

dog.prototype = new Animal();

console.log(new dog('xiao', 'gold')); // Animal { name: 'gold', say: [Function] }
(new dog('xiao')).action() //running

apply 传递一个数组或arguments,而call就要一个个地传过this

案例

es5中的继承es5

function Reactangle(length,width) {
  this.length = length;
  this.width = width;
}

Reactangle.prototype.getArea = function(){
  return this.length * this.width;
}

function Square(length) {
  Reactangle.call(this.length,length);
}

Square.prototype = Object.create(Reactangle.prototype,{
  constructor: {
    value:Square,
    enumerable:true,
    writeable:true,
    configurable:true
  }
});

var square = new Square(3);

console.log(square.getArea());
console.log(square instanceof Square);
console.log(square instanceof Reactangle);

在es6中实现继承prototype

class Reactangle {
   constructor(length,width) {
     this.length = length;
     this.width = width;
   }
   
   getArea() {
      return this.length * this.width;
   }
}

class Square extends Reactangle {
  constructor(length) {
    // 等价于 Reactangle.call(this.length,length)
    super(length,length);
  }
}

var square = new Square(3);

console.log(square.getArea()); // 9
console.log(square instanceof Square); // true
相关文章
相关标签/搜索