apply call bind 共同点
- 都是用来改变函数的this对象的指向的。
- 第一个参数都是this要指向的对象。
- 都可以利用后续参数传参
apply
语法:apply(thisArg, [argsArray])
var user = {
greet: "hello",
greetUser: function (userName) {
console.log(this.greet + " " + userName);
},
};
var greetHi = {
greet: "hi",
};
user.greetUser.apply(greetHi, "zhouJin"); // hi zhouJin
call
语法:call(thisArg, [argsArray])
var user = {
greet: "hello",
greetUser: function (userName) {
console.log(this.greet + " " + userName);
},
};
var greetHi = {
greet: "hi",
};
user.greetUser.call(greetHi, "zhouJin"); // hi zhouJin
bing
用法: 使用bind方法,可以为函数绑定this值,然后作为一个新的函数返回
var user = {
greet: "hello",
greetUser: function (userName) {
console.log(this.greet + " " + userName);
},
};
var greetHi = user.greetUser.bind({ greet: "hi" });
greetHi("zhouJin"); // hi zhouJin