美文网首页
apply()和call()的使用

apply()和call()的使用

作者: Axiba | 来源:发表于2016-09-01 11:02 被阅读33次

1、call :

  • funA.call(funB, arg1, arg2, ...)
  • 例子
//参照理解的dem01
function funB (arg1, arg2){
    alert(arg1+arg2);
}
function funA (arg1, arg2){
    alert(arg1-arg2);
}
funB.call(funA, 100, 100);
//参照理解的demo2
var a = {0:1, 1:"yjc", length: 2}; 
a.slice(); // Uncaught TypeError: a.slice is not a function(…)
Array.prototype.slice.call(a); //[1, "yjc"]
//参照理解的demo3
var pet = {
      word:'...',
      speak: function(say){
          alert(say+this.word);
      }
}; 
var dog ={
      word:'Wang'
}
pet.speak.call(dog, 'Speak');
//参照理解的demo4
function Pet(word){
     this.word=word;
      this.speak: function(){
          alert(this.word);
      }
}; 
function Dog(word){
      Pet.call(this, 'word);
}

var dog  = new Dog('Wang');
dog.speak();

2、apply

  • funA.apply(funB, arr[arg1, arg2, ..])
  • 例子:给每一个log消息添加一个"(app)"的前辍:
function log(){ 
    var args = Array.prototype.slice.call(arguments); 
    args.unshift('(app)'); 
    console.log.apply(console, args); 
}
// arugments是一个伪数组,然后会将他转化成为标准数组。通常方法是使用Array.prototype.slice

3、区别

  • 不同只是参数使用方式不同而已
  • (1 都是 Function.proptotype 的一个方法
  • (2 作用相同,只是使用方式不同而已
  • (3 都是借用别人的方法,像调用自己一样

4、简单的应用

  • 例如之前看过的一个简单的面试题,现在有这样一个方法:
  var Info = {
      flag: 1,
      getFlagInfo: function(){
            return this.flag;
      }
  }

然后通过下面的代码去调用:

console.log(Info.getFlagInfo());

var func = Info.getFlagInfo();
console.log(func());

这时候会发现第一个打印出1而第二个打印undefined,因为func在windows中被提前执行而当时拿不到this.flag,我们也许可以通过bind,比如:

var func = Info.getFlagInfo.bind(Info);

但是这样在旧浏览器的时候会有兼容性的问题,所以可以通过apply来解决:

Function.prototype.bind = Function.prototype.bind || function(context){
  let self = this;
  return function(){
      self.apply(context, arguments);  
  }
}

相关文章

网友评论

      本文标题:apply()和call()的使用

      本文链接:https://www.haomeiwen.com/subject/jtvcettx.html