- 首先call、apply、bind都是用来显式绑定对象,可以改变函数的this对象指向
- 第一个参数都是this要指向的对象(函数执行时,this将指向这个对象),后续参数用来传实参。
var person1 = {
name: "小王",
gender: "男",
age: 24,
say: function (school, grade) {
alert(this.name + " , " + this.gender + " ,今年" + this.age + " ,在" + school + "上" + grade);
}
}
var person2 = {
name: "小红",
gender: "女",
age: 18
}
如果是通过call的参数进行传参,是这样的:
person1.say.call(person2, "实验小学", "六年级");
如果是通过apply的参数进行传参,是这样的:
person1.say.apply(person2, ["实验小学", "六年级"]);
而bind有些区别,bind绑定一个this给函数,并生成一个新函数,直接调用即可。bind的参数使用方法和call相同
const module = {
x: 42,
getX: function() {
return this.x;
}
};
const unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined
const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// expected output: 42
this.x = 9; // 在浏览器中,this 指向全局的 "window" 对象
var module = {
x: 81,
getX: function() { return this.x; }
};
module.getX(); // 81
var retrieveX = module.getX;
retrieveX();
// 返回 9 - 因为函数是在全局作用域中调用的
// 创建一个新函数,把 'this' 绑定到 module 对象
// 新手可能会将全局变量 x 与 module 的属性 x 混淆
var boundGetX = retrieveX.bind(module);
boundGetX(); // 81