首页 > 其他分享 >call, apply, bind 方法 改变 this

call, apply, bind 方法 改变 this

时间:2022-10-08 14:35:48浏览次数:49  
标签:bind 34 person say call apply

 1 var person = {
 2       name: 'shiyujian',
 3       age: 34,
 4       say: function(from, to) {
 5           console.log(this.name + " " + this.age + " " + from + " " + to);
 6       }
 7 };
 8 var other1 = {
 9       name: 'wanglin',
10       age: 20
11 }
12 person.say.call(other,'上海','北京'); // tom 34 上海 北京
13 person.say.apply(other,['上海','北京']); // tom 34 上海 北京
14 person.say.bind(other,'上海','北京')(); // tom 34 上海 北京
15 person.say.bind(other,['上海','北京'])(); // tom 34 上海 北京 undefined

我们知道,JS中函数也是对象,这三个方法就是函数对象的方法,都可以改变函数执行的上下文环境,即改变 this 对象的绑定,不同的是:

call 和 apply 都是改变同时调用,但是 bind 只是改变 this 对象并返回一个新的函数,不会直接调用
call 和 bind 的参数都是直接放进去,但是 apply 必须通过数组传参

标签:bind,34,person,say,call,apply
From: https://www.cnblogs.com/shiyujian/p/14837668.html

相关文章