1.apply 、 call 、bind 三者都是用来改变函数的this对象的指向的;
2.apply 、 call 、bind 三者第一个参数都是this要指向的对象,也就是想指定的上下文;
3.apply 、 call 、bind 三者都可以利用后续参数传参;
bind是返回对应函数,便于稍后调用;apply、call则是立即调用 。
call一般表示函数的调用,要调用函数,fn.call(),此时this是fn.call()的第一个参数,也就是函数本身。
call()方法的作用和 apply() 方法类似,区别就是call()方法接受的是参数列表,而apply()方法接受的是一个参数数组。
func.call(this, arg1, arg2);
func.apply(this, [arg1, arg2])
bind实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//复杂的
Function.prototype.mybind = function (context) {
let self = this
var args = Array.prototype.slice.call(arguments, 1)
console.log(args)
return function () {
var newArgs = Array.prototype.slice.call(arguments)
self.apply(context, args.concat(newArgs));
};
}
function sayHello(name, name2) {
console.log(`${name},${name2}`)
}
let geet = sayHello.mybind(null, 'John')
geet('Doe', 'nnn')
// 简单
Function.prototype.myBind = function (context) {
let self = this
return function () {
self.apply(context, arguments)
}
}
function say(a, b) {
console.log(a, b)
}
let gg = say.myBind()
gg('我', '你')
</script>
</body>
</html>