call、bind、apply的区别

标签:2024-05-16 10:15:26

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
来源:博客网 转载请注明出处!

活跃用户

shine
Ta还没有签名
暖色调
Ta还没有签名
归去来兮
Ta还没有签名
火般冷
Ta还没有签名

友情链接


Warning: Smarty error: unable to read resource: "../../../templates/default/./common/foot/footer_index.htm" in /usr/home/hyu3925200001/htdocs/common/smarty/Smarty.class.php on line 1093

Warning: Smarty error: unable to read resource: "../../../templates/default/./common/foot/footer_index.htm" in /usr/home/hyu3925200001/htdocs/common/smarty/Smarty.class.php on line 1093