Apply、Call、Bind 三者之间对this的异同
查看这些方法 Function.prototype.call(), Function.prototype.apply(),Function.prototype.bind().
- Call 调用该函数并允许您逐个传递参数。
- Apply 调用该函数并允许您将参数作为数组传递。
- Bind 返回一个新的函数,允许你传入一个这个数组和任意数量的参数。
Apply vs. Call vs. Bind Examples
Call
123456789var person1 = {firstName: 'Jon', lastName: 'Kuperman'};var person2 = {firstName: 'Kelly', lastName: 'King'};function say(greeting) {console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);}say.call(person1, 'Hello'); // Hello Jon Kupermansay.call(person2, 'Hello'); // Hello Kelly KingApply
123456789var person1 = {firstName: 'Jon', lastName: 'Kuperman'};var person2 = {firstName: 'Kelly', lastName: 'King'};function say(greeting) {console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);}say.apply(person1, ['Hello']); // Hello Jon Kupermansay.apply(person2, ['Hello']); // Hello Kelly KingBind
123456789101112var person1 = {firstName: 'Jon', lastName: 'Kuperman'};var person2 = {firstName: 'Kelly', lastName: 'King'};function say() {console.log('Hello ' + this.firstName + ' ' + this.lastName);}var sayHelloJon = say.bind(person1);var sayHelloKelly = say.bind(person2);sayHelloJon(); // Hello Jon KupermansayHelloKelly(); // Hello Kelly King
Call 和 apply 是可互换的,只要要注意是数组还是以逗号分隔的参数。
所以区别Call与Apply最直接的方法就是:Call参数以逗号分割,而Apply参数为数组。
Bind (有些不一样)它返回的是一个新函数, Call 和 Apply是立即执行当前函数。