javascript中的call(),它可以用来调用所有者对象作为参数的方法,通过 call(),您能够使用属于另一个对象的方法。
var person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var person1 = {
firstName:"Bill",
lastName: "Gates"
}
var person2 = {
firstName:"Steve",
lastName: "Jobs"
}
person.fullName.call(person2); //打印结果是"Steve Jobs"
以上案例总结 作用一:call()可以调用某一函数
var person = {
fullName: function(city, country) {
console.log(this)
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName:"Bill",
lastName: "Gates"
}
var person2 = {
firstName:"Steve",
lastName: "Jobs"
}
person.fullName.call() //这样调用this指向window
person.fullName.call(person1) //这样调用this指向person1这个对象
以上案例总结 作用二:call()可以这个函数的this指向。
另外,call()也可以接受参数,比如:
var person = {
fullName: function(city, country) {
console.log(this)
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName:"Bill",
lastName: "Gates"
}
var person2 = {
firstName:"Steve",
lastName: "Jobs"
}
person.fullName.call(person1,'CHINA','BeiJing') //打印结果为"Bill Gates,CHINA,BeiJing"