/*
call修改this指针的指向
()内可以接收多个参数
*/
var person = {
fullName: function() {
console.log('this',this)
return this.firstName + " " + this.lastName;
}
}
var person1 = {
firstName:"Bill",
lastName: "Gates",
}
person.fullName() //此时this指向person对象信息
person.fullName.call(person1); //此时的this指向person1对象信息 将返回 "Bill Gates"
var person2 = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person3 = {
firstName:"Bill",
lastName: "Gates"
}
let str = person2.fullName.call(person3, "Seattle", "USA");
console.log(str)//Bill Gates,Seattle,USA
/*
apply修改this指针的指向
()内用数组的方式接收参数
*/
var person4 = {
fullName: function() {
console.log('this',this)
return this.firstName + " " + this.lastName;
}
}
var person5 = {
firstName:"Bill",
lastName: "Gates",
}
person4.fullName() //此时this指向person4对象信息
person4.fullName.apply(person5); //此时的this指向person5对象信息 将返回 "Bill Gates"
var person6 = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person7 = {
firstName:"Bill",
lastName: "Gates"
}
let str1 = person6.fullName.apply(person7, ["Seattle", "USA"]);
console.log(str1)//Bill Gates,Seattle,USA