先看明白下面:
例 1
let name = "小王",
age = 17;
const obj = {
name: "小张",
objAge: this.age,
myFun: function () {
console.log(this.name + "年龄" + this.age);
},
};
obj.objAge; // 17
obj.myFun(); // 小张年龄 undefined
例 2
let fav = "盲僧";
function shows() {
console.log(this.fav);
}
shows(); // 盲僧
比较一下这两者 this 的差别,第一个打印里面的 this 指向 obj ,第二个全局声明的 shows() 函数 this 是 window ;
1,call()、apply()、bind() 都是用来重定义 this 这个对象的!
如:
let name = "小王",
age = 17;
const obj = {
name: "小张",
objAge: this.age,
myFun: function () {
console.log(this.name + "年龄" + this.age);
},
};
const db = {
name: "德玛",
age: 99,
};
obj.myFun.call(db); // 德玛年龄 99
obj.myFun.apply(db); // 德玛年龄 99
obj.myFun.bind(db)(); // 德玛年龄 99
以上出了 bind 方法后面多了个 () 外 ,结果返回都一致!
由此得出结论,bind 返回的是一个新的函数,你必须调用它才会被执行。
2,对比call 、bind 、 apply 传参情况下
let name = "小王",
age = 17;
const obj = {
name: "小张",
objAge: this.age,
myFun: function (fm, t) {
console.log(this.name + "年龄" + this.age, "来自" + fm + "去往" + t);
},
};
const db = {
name: "德玛",
age: 99,
};
obj.myFun.call(db, "成都", "上海"); // 德玛 年龄 99 来自 成都去往上海
obj.myFun.apply(db, ["成都", "上海"]); // 德玛 年龄 99 来自 成都去往上海
obj.myFun.bind(db, "成都", "上海")(); // 德玛 年龄 99 来自 成都去往上海
obj.myFun.bind(db, ["成都", "上海"])(); // 德玛 年龄 99 来自 成都, 上海去往 undefined
微妙的差距!
从上面四个结果不难看出:
call 、bind 、 apply 这三个函数的第一个参数都是 this 的指向对象,第二个参数差别就来了:
call 的参数是直接放进去的,第二第三第 n 个参数全都用逗号分隔,直接放到后面 obj.myFun.call(db,’成都’, … ,’string’ )。
apply 的所有参数都必须放在一个数组里面传进去 obj.myFun.apply(db,[‘成都’, …, ‘string’ ])。
bind 除了返回是函数以外,它 的参数和 call 一样。
当然,三者的参数不限定是 string 类型,允许是各种类型,包括函数 、 object等等!
常见使用场景
光看区别不够,这几个方法真正好用的是”借用”和”预设”:
1. 借用数组方法处理类数组
arguments、DOM 的 NodeList 不是真数组,没有 push / slice。用 call 借用数组方法:
// 把 arguments 转成真正的数组
const args = Array.prototype.slice.call(arguments);
// 或更简单
const args2 = [].slice.call(arguments);
// ES6 之后也可写成 [...arguments] 或 Array.from(arguments)
2. 求数组最大 / 最小值
Math.max 接收的是散参数,配合 apply 把数组”摊开”:
const nums = [3, 7, 1, 9];
Math.max.apply(null, nums); // 9
// ES6 之后更直观:Math.max(...nums)
3. 继承里调用父类构造函数
子类构造函数里用 call 把父类的 this 指向子类实例:
function Parent(name) {
this.name = name;
}
function Child(name, age) {
Parent.call(this, name); // 借用父类构造,绑定 this
this.age = age;
}
4. bind 预设参数(柯里化)
bind 除了绑定 this,还能提前固定部分参数,返回新函数:
function add(a, b) {
return a + b;
}
const add10 = add.bind(null, 10); // this 用 null,预设第一个参数为 10
add10(5); // 15
小结:
call/apply立即执行、bind返回待执行函数;call与bind参数逐个传,apply参数放数组。日常最常用就是”借用方法”和”预设参数”这两招。