call和apply

  

在js中经常会看到call和apply,他们实际上就是用于改变this的上下文

经典例子

 

function pet(words)

{

   this.words=words;

   this.speak=function()

  {

      console.log(this.words);//正常情况下,此

  }

}

function Dog(words)

{

  pet.call(this,words);//此处将pet中的上下文this指向dog

//pet.apply(this,arguments)apply和call的 区别是一个参数是字符串,一个是数组

}

var dog=new Dog("wang");

dog.speak();

 

运行代码,结果:wang

posted @ 2016-01-04 18:23  fly1111345我  阅读(126)  评论(0编辑  收藏  举报