You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
varperson={lastName: '哪吒'};functioninvite(greeting1,greeting2){console.log(greeting1+" "+this.lastName+" "+greeting2);}invite.call(person,"Hello","How are you");// Hello 哪吒 How are you
varperson={lastName: '哪吒'};functioninvite(greeting1,greeting2){console.log(greeting1+" "+this.lastName+" "+greeting2);}invite.apply(person,["Hello","How are you"]);// Hello 哪吒 How are you
varemployee1={firstName: "a",lastName: "aa"};varemployee2={firstName: "d",lastName: "dd"};functioninvite(greeting1,greeting2){console.log(greeting1+" "+this.firstName+" "+this.lastName+", "+greeting2);}varinviteEmployee1=invite.bind(employee1);// 创建新函数并绑定对象varinviteEmployee2=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之间的区别:
apply()方法会接收两个参数:函数内this的值和一个参数数组。第二个参数可以是Array的实例,也可以是arguments对象。
ES5定义一个新方法:bind()。(bind方法会创建一个新的函数实例,其this值会被绑定到传给bind()的对象)
call和apply是可以互换的,两者都立即执行当前函数。您需要决定是否更容易发送数组或逗号分隔的参数列表。而bind创建一个新的函数,该函数将this设置为传递给bind()的第一个参数。
call()和apply()方法都会以指定的this值来调用函数,即会设置调用函数时函数体内this对象的值。call()和apply()真正强大的地方并不是给函数传参,而是控制函数 调用上下文 即函数体内this值的能力。
使用call()和apply()的好处是可以将任意对象设置为任意函数的作用域,这样对象可以不用关心方法。
未完结!更多内容尽情期待下一节~
【深入理解JS核心技术】欢迎各位观众老爷,求点赞,求关注,求转发~
The text was updated successfully, but these errors were encountered: