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

原文地址:https://www.cnblogs.com/openflyme/p/5099901.html