继承

call实现继承

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

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的继承方法就会失效,因此我们一般使用混合的写法。

让子的原型链指向父的实例(父实例化的对象)
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就要一个个地传过

案例

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中实现继承

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

learningCoder
42 声望1 粉丝