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

138 阅读1分钟

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"); //"Bill Gates,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"]); // 返回"Bill Gates,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")(); // "Bill Gates,Seattle,USA"