1、都是用来改变函数执行时的上下文,再具体一点就是改变函数运行时的this指向
2、区别:参数书写方式不同
call(thisObj, arg, arg2, arg3);
apply(thisObj, [args]);
bind(thisObj,arg, arg2, arg3)(); //bind 返回的是一个新的函数,必须调用它才会被执行。
Call
let p1 = {
firstName: 'John',
lastName: 'Smith'
};
let p2 = {
firstName: 'Ann',
lastName: 'Brown'
};
function sayWelcome(greeting) {
console.log(`${greeting} ${this.firstName} ${this.lastName}`);
}
sayWelcome.call(p1, 'Welcome'); // Welcome John Smith
sayWelcome.call(p2, 'Welcome'); // Welcome Ann Brown
Apply
let p1 = {
firstName: 'John',
lastName: 'Smith'
};
let p2 = {
firstName: 'Ann',
lastName: 'Brown'
};
function sayWelcome(greeting) {
console.log(`${greeting} ${this.firstName} ${this.lastName}`);
}
sayWelcome.apply(p1, ['Welcome']); // Welcome John Smith
sayWelcome.apply(p2, ['Welcome']); // Welcome Ann Brown
Bind
let p1 = {
firstName: 'John',
lastName: 'Smith'
};
let p2 = {
firstName: 'Ann',
lastName: 'Brown'
};
function sayWelcome(greeting,greeting2) {
console.log(`${greeting} ${this.firstName} ${this.lastName}`)
}
sayWelcome.bind(p1, 'Welcome')(); // Welcome John Smith
sayWelcome.bind(p2, 'Welcome')(); // Welcome Ann Brown
原文出处:http://www.dongblog.com/notes/58.html
来源:博客网 转载请注明出处!