Bind & Call & Apply
-
bind/call/apply三个方法都是可以改变对应函数的this指向的,
-
bind方法通过该函数调用并且返回一个新的函数,
新的函数已经修改了this指向,只有调用这个新的函数,函数体才会被执行。
(会创建一个新函数。当这个新函数被调用时,bind() 的第一个参数将作为它运行时的 this,之后的一序列参数将会在传递的实参前传入作为它的参数)
-
call/apply方法是会直接绑定this并进行调用的,
调用的时候,函数内部的this指向call/apply的第一个参数,两者的区分主要在于传参的格式上
call 和 bind 区别
- call将立即执行该函数
- bind不执行函数,只返回一个可供执行的函数
bind用法
func.bind(thisArg[, arg1[, arg2[, ...]]]) // bind 用法
var publicAccounts = {
name: 'seriousLose',
author: 'long',
subscribe: function (subscriber) {
console.log(subscriber + this.name)
}
}
publicAccounts.subscribe('小明') // 输出结果: "小明 seriousLose"
var subscribe1 = publicAccounts.subscribe.bind({
name: 'fly',
author: 'long'
}, '小明 ');
subscribe1() // 输出结果: "小明 fly"
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
call 和 apply 区别
- call和apply的第一个参数会绑定到函数体的this上,
- 如果 不传参数,例如 fun.call(),非严格模式,this默认还是绑定到全局对象
- call函数接收的是一个参数列表,apply函数接收的是一个参数数组;
- func.call(thisArg, arg1, arg2, …) // call 用法
- func.apply(thisArg, [arg1, arg2, …]) // apply 用法
var person = {
"name": "feifei"
};
function changeJob(company, work) {
this.company = company;
this.work = work;
};
changeJob.call(person, '百度', '程序员');
console.log(person.work); // '程序员’
// changeJob.apply(person, ['百度', '测试']);
// console.log(person.work); // '测试'
var number = 1,
var string = 'seriousLose';
function getThisType() {
var number = 3;
console.log('this指向内容', this);
console.log(typeof this);
}
getThisType.call(number);
getThisType.apply(string); // 输出结果
// this指向内容 [Number: 1] // object
// this指向内容 [String: 'seriousLose'] // object
const obj = {};
fun.call(obj, "arg1","arg2",...);
const obj = {};
fun.call(obj, ["arg1","arg2",...]);
// 用bind则需要手动调用一次
const obj = {};
fun.bind(target, "arg1","arg2",...)();
const personA = {
name: "A",
say: function () {
console.info("my name is " + this.name);
},
};
const personB =
name: "B"
};
personA.say.call(personB);
// my name is B
// 因为call方法将personA.say函数中的this绑定到了personB,故输出的时候,this.name也就是personB的name
掌握 JavaScript 中的 this,call,apply 的原理
https://www.notion.so/serious-lose/JS-Bind-Call-Apply-eb958b614aad4ec79f1cbdca8634cb06