Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【深入理解JS核心技术】3. 调用、应用和绑定有什么区别 #15

Open
webVueBlog opened this issue Apr 30, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

call, apply, bind之间的区别:

  1. call()方法调用一个给定this值和参数一一提供的函数。
var person = { lastName: '哪吒' };

function invite(greeting1, greeting2) {
 console.log(
  greeting1 + " " + this.lastName + " " + greeting2
 );
}

invite.call(person, "Hello", "How are you"); // Hello  哪吒 How are you
  1. apply()使用给定值调用函数this并允许您将参数座位数组传递

apply()方法会接收两个参数:函数内this的值和一个参数数组。第二个参数可以是Array的实例,也可以是arguments对象。

function sum(num1, num2) {
 return num1 + num2;
}

function callSum1(num1, num2) {
 return sum.apply(this, arguments); // 传入arguments对象
}

function callSum2(num1, num2) {
 return sum.apply(this, [num1, num2]); // 传入数组
}

console.log(callSum1(10, 10)); // 20
console.log(callSum2(10, 10)); // 20
var person = { lastName: '哪吒' };

function invite(greeting1, greeting2) {
 console.log(
  greeting1 + " " + this.lastName + " " + greeting2
 );
}

invite.apply(person, ["Hello", "How are you"]); // Hello  哪吒 How are you
  1. bind()返回一个新函数,允许您传递任何数量的参数

ES5定义一个新方法:bind()。(bind方法会创建一个新的函数实例,其this值会被绑定到传给bind()的对象)

var employee1 = { firstName: "a", lastName: "aa" };
var employee2 = { firstName: "d", lastName: "dd" };

function invite(greeting1, greeting2) {
  console.log(
    greeting1 + " " + this.firstName + " " + this.lastName + ", " + greeting2
  );
}

var inviteEmployee1 = invite.bind(employee1); // 创建新函数并绑定对象
var inviteEmployee2 = invite.bind(employee2);
inviteEmployee1("Hello", "How are you?"); // Hello a aa, How are you?
inviteEmployee2("Hello", "How are you?"); // Hello d dd, How are you?

call和apply是可以互换的,两者都立即执行当前函数。您需要决定是否更容易发送数组或逗号分隔的参数列表。而bind创建一个新的函数,该函数将this设置为传递给bind()的第一个参数。

call()和apply()方法都会以指定的this值来调用函数,即会设置调用函数时函数体内this对象的值。call()和apply()真正强大的地方并不是给函数传参,而是控制函数 调用上下文 即函数体内this值的能力。

window.color = "red";
let o = {
 color: 'blue'
};

function sayColor() {
 console.log(this.color);
}

sayColor(); // red

sayColor.call(this); // red
sayColor.call(window); // red
sayColor.call(o); // blue

使用call()和apply()的好处是可以将任意对象设置为任意函数的作用域,这样对象可以不用关心方法。

未完结!更多内容尽情期待下一节~

【深入理解JS核心技术】欢迎各位观众老爷,求点赞,求关注,求转发~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant