先是温故时间:
1、通过 call 、 apply 、 bind 我们可以修改函数绑定的 this ,使其成为我们指定的对象。通过这些方法的第一个参数我们可以显式地绑定 this
2、用法:
func.call(thisArg,arg1,arg2,....)
func.apply(thisArg,[arg1,arg2,....])
func.bind(thisArg[, arg1[, arg2[, ...]]])
call 和 apply 的区别是 call 方法接受的是参数列表,而 apply 方法接受的是一个参数数组。
而 bind 方法是设置 this 为给定的值,并返回一个新的函数,且在调用新函数时,将给定参数列表作为原函数的参数序列的前若干项。
bind做了什么
创建一个新函数
新函数的this指向bind()的第一个参数
bind的其余参数作为新函数的参数供调用时使用
基础使用
function foo(name){
return `${name}`+this.age
}
let Foos = foo.bind({age:18})
Foos('tcc') //tcc18
手写bind
ES5方式
Function.prototype.bind = Function.prototype.bind || function() {
var self = this
var rest1 = Array.prototype.slice.call(arguments)
var context = rest1.shift()
return function() {
var rest2 = Array.prototype.slice.call(arguments)
return self.apply(context, rest1.concat(rest2))
}
}
ES6方式
Function.prototype.bind = Function.prototype.bind || function(...rest1){
const self = this
const thisArg = rest1.shift()
return function(...rest2){
return self.apply(thisArg,[...rest1,...rest2])
}
}
注意: 如果你把 null 或 undefined 作为 this 的绑定对象传入 call 、 apply 、 bind ,这些值在调用时会被忽略,实际应用的是默认绑定规则。
var a = 'hello'
function foo() {
console.log(this.a)
}
foo.call(null) // 浏览器中输出: "hello"