apply#####
function Animal(name,age){
  this.name = name;
  this.age = age;
  this.showName = function(){
     console.log(this.name)
  };
  this.showAge = function(){
     console.log(this.age)
  };
}

function NewAnimal(name,age){
  Animal.apply(this,[name,age])
}

var dog = new NewAnimal('小狗',6)
dog.showName()//小狗
dog.showAge()//6
call#####
function Animal(name,age){
  this.name = name;
  this.age = age;
  this.showName = function(){
     console.log(this.name)
  };
  this.showAge = function(){
     console.log(this.age)
  };
}

function NewAnimal(name,age){
  Animal.call(this,name,age)
}

var dog = new NewAnimal('小狗',6)
dog.showName()//小狗
dog.showAge()//6

总结:####

Animal.apply(NewAnimal, [参数1,参数2...])   Animal 为即将被借用的对象   NewAnimal 为借用者  后面的数组代表方法内部传入的参数

Animal.call(NewAnimal, 参数1,参数2....)   Animal 为即将被借用的对象   NewAnimal 为借用者  后面的参数123为方法内部传入的参数

两个实现的效果都一样,都是改变了this的指向,但是它们的传参方式不一样
posted on 2018-11-29 12:23  佑之以航  阅读(106)  评论(0编辑  收藏  举报