前言:开发中常常使用call、apply、bind方法,可是偶尔仍是会忘了它们之间的差异,这里作个总结方便本身回顾。数组
JavaScript中全部函数都继承了函数原型(Function.prototype)中的 call 与 apply 两个方法,call和apply用于改变函数调用时函数内部this的指向。app
第一部分:apply、call方法dom
语法:func.apply(thisarg, argsArray),调用一个函数, 指定的this
值,和一个数组做为函数调用的参数。函数
参数:this
thisarg: 调用func函数时,函数内部真正的this指向,非严格模式下该值为null或undifined时,this默认指向window对象。spa
argsArray:调用func函数时传递的参数列表(以数组形式),该值为null或undifined时,表示不传入任何参数。prototype
返回值:返回指定this和参数的函数的执行结果。code
举例1:改变this的指向对象
var name = 'jack' function SayHello() { console.log(this.name + ' say hello!') } //直接执行方法,内部this指向window SayHello() //jack say hello! var stu = { name:'john' } //使用apply方法指定SayHello的调用对象为stu,方法中的this就指向stu SayHello.apply(stu) //john say hello!
举例2:调用别的对象的方法blog
var person = { name: 'jack', introduce: function(){ console.log('my name is ' + this.name) } } var manager = { name: 'jone' } //此时的manager对象没有introduce,可是咱们又想调用此方法。 person.introduce.apply(manager)
此例中,manager对象中没有introduce方法,但同时又想调用此方法,咱们经过apply改变introduce方法中this的指向,从而实现方法的调用。
举例3:参数为数组的妙用
1.数组的拼接
/* 1.数组push方法的参数是数组一个个的元素并不是完整的数组 2.若是直接array1.push(array2)程序会报错 3.apply要求参数是数组,这里咱们就能够借用apply简化数组的追加运算。 */ var array1 = [12 , "foo" , -2458] var array2 = ["Doe" , 555 , 100]; Array.prototype.push.apply(array1, array2);
2.最大最小数求值
/* 1.Math对象的max方法的参数是数组。 2.数组自己没有max方法,借助Math对象的max方法,apply调用传入数组完美解决。 */ var numbers = [5, 458 , 120 , -215 ] var maxInNumbers = Math.max.apply(Math, numbers), //458
apply和call的区别:对于 apply、call 两者而言,做用彻底同样,只是接受参数的方式不同,apply接收的是数组,call接收的是参数列表。
举例:数组最大值
/* apply接收参数为数组 call接收参数为参数列表 */ var numbers = [5, 458 , 120 , -215 ]; var maxInNumbers = Math.max.apply(Math, numbers), //458 maxInNumbers = Math.max.call(Math, 5, 458, 120, -215); //458
第二部分:bind方法
与apply、call区别:
bind()也能够改变调用函数体内this的指向,区别apply、call调用方法当即执行,bind()执行结果是返回一个函数并不是当即执行。
语法:func.bind(thisarg, arg...), bind()建立一个新的函数, 函数中this为绑定时指定的值,参数列表为绑定时指定的参数序列。
参数:
thisarg: 被绑定函数执行时,函数体内真正的this指向。
arg...:被绑定函数执行时,传递给函数的参数列表。
返回值:返回一个指定this和参数列表的函数。
在定时器,dom事件中都存在回到函数,咱们一般会使用_this,that,self等暂存this引用,当上下文改变后,咱们依然能够调用。
举例1:绑定到回到函数上
/* 这里给class为name的dom元素绑定了单击事件 click事件只有在真正点击dom元素时候才会触发,此时回到函数中的this表明当前dom元素。 */ var foo = { count: 1, clickEvent: function () { $('.name').on('click', function (event) { console.log(this.count) //undefined }); } } /* 经过_this = this保留this指向,回掉函数中的this依旧指向foo对象 */ var foo = { count: 1, clickEvent: function () { var _this = this $('.name').on('click', function (event) { console.log(_this.count) //1 }); } } /* 经过bind()函数绑定函数执行时this的指向。 */ var foo = { count: 1, clickEvent: function () { $('.name').on('click', function (event) { console.log(this.count) //1 }).bind(this) } }
总结:
做用:apply 、 call 、bind 均可以改变调用函数中this的指向。
参数:apply 、 call 、bind 第一个参数都是函数调用时所指向的this值,后续参数为函数执行时传入的参数列表。
区别:bind 是返回对应函数,便于稍后调用;apply 、call 则是当即调用 。