美文网首页
apply()、call() 与 bind()用法

apply()、call() 与 bind()用法

作者: milletmi | 来源:发表于2018-10-11 13:18 被阅读0次

在 javascript 中,call 和 apply 都是为了改变某个函数运行时的上下文(context)而存在的,换句话说,就是为了改变函数体内部 this 的指向。JavaScript 的一大特点是,函数存在「定义时上下文」和「运行时上下文」以及「上下文是可以改变的」这样的概念。
bind() 方法与 apply 和 call 很相似,也是可以改变函数体内 this 的指向。

apply 和 call 改变this指向


例如:

  let person = {
      name : 'Amy',
      say : function(){
             console.log('hello everybody , my name is '+ this.name)
            }
    }
   person.say()//hello everybody , my name is Amy
   let jayden = {
       name : 'jayden'
   }
   person.say.call(jayden)//hello everybody , my name is jayden
   person.say.apply(jayden)//hello everybody , my name is jayden

apply 和 call 的区别


apply()call() 作为所有函数的方法,定义为:在指定this值与参数的情况下调用某个函数或方法。两者的区别是:
call()方法接受的是若干个参数的列表 :func.call(this, arg1, arg2);
apply()方法接受的是一个包含多个参数的数组 :func.apply(this, [arg1, arg2])
这两个方法的关键点在于指定this与参数
call的常用用法:
验证是否是数组(前提是toString()方法没有被重写过)

functionisArray(obj){ 
    return Object.prototype.toString.call(obj) === '[object Array]' ;
}

类(伪)数组使用数组方法

var domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));

apply的常用用法:
1、数组间的追加

let arr1 = [1, 2, 3, 4]
let arr2 = [5, 6, 7, 8]
arr1.push.apply(arr1, arr2) // [1, 2, 3, 4, 5, 6, 7, 8]

1、数组中的最大值最小值

let arr1 = [1, 2, 3, 4]
Math.max.apply(Math, arr1) // 4
Math.min.apply(Math, arr1) // 1

bind的常用用法:
bind()方法会创建一个新函数,称为绑定函数,当调用这个绑定函数时,绑定函数会以创建它时传入 bind()方法的第一个参数作为 this,传入 bind() 方法的第二个以及以后的参数加上绑定函数运行时本身的参数按照顺序作为原函数的参数来调用原函数。

//在常见的单体模式中,通常我们会使用 _this , that , self 等保存 this ,这样我们可以在改变了上下文之后继续引用到它。
let person = {
    name : 'Amy',
    eventBind : function(){
            var _this = this;
            $('.someClass').on('click',function(event) {
                /* Act on the event */
                console.log(_this.name);     //1
            });
    }
}
//使用 bind() 可以更加优雅的解决这个问题
let person = {
    name : 'Amy',
    eventBind : function(){
            $('.someClass').on('click',function(event) {
                /* Act on the event */
                console.log(_this.name);     //1
            }).bind(this);
    }
}

相关文章

网友评论

      本文标题:apply()、call() 与 bind()用法

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