js call()、apply()、bind()的区别和使用

时间:2020-12-15 12:11:12   收藏:0   阅读:2

js call()、apply()、bind()的区别和使用

写在前面:

call:

目的: 改变函数运行时的上下文(context),即this指向
说人话: 就是“劫持”(继承)别人的方法
例子:person.fullName.call(person1) 即 对象person1继承了person的fullName方法

var person = {
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
}
var person1 = {
    firstName:"Bill",
    lastName: "Gates",
}
person.fullName.call(person1);  // 将返回 "Bill Gates"

另外: call()也可以传递其他参数:call(thisObj, arg1, arg2, arg3, arg4);

var person = {
  fullName: function(city, country) {
    return this.firstName + " " + this.lastName + "," + city + "," + country;
  }
}
var person1 = {
  firstName:"Bill",
  lastName: "Gates"
}
person.fullName.call(person1, "Seattle", "USA");

打印结果:
技术图片

apply: 同 call

目的: 改变函数运行时的上下文(context),即this指向
例子:person.fullName.apply(person1) 即 对象person1继承了person的fullName方法
和call的区别: 传递其他参数时需要使用[]
传递其他参数:apply(thisObj, [arg1, arg2, arg3, arg4]);

var person = {
  fullName: function(city, country) {
    return this.firstName + " " + this.lastName + "," + city + "," + country;
  }
}
var person1 = {
  firstName:"Bill",
  lastName: "Gates"
}
person.fullName.apply(person1, ["Seattle", "USA"]);

打印结果:
技术图片

bind: 同call、apply

目的: 改变函数运行时的上下文(context),即this指向
和call、apply的区别: 使用的返回值是个方法,也就是bind(thisObj)()实现
传递其他参数:bind(thisObj, arg1, arg2, arg3, arg4)();

var person = {
  fullName: function(city, country) {
    return this.firstName + " " + this.lastName + "," + city + "," + country;
  }
}
var person1 = {
  firstName:"Bill",
  lastName: "Gates"
}
person.fullName.bind(person1, "Seattle", "USA")();

打印结果:
技术图片

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!