call:它的作用是改变调用者的this指向到指定的对象上面,并将调用者执行之后返回给自己
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");
这里的调用者指的是person.fullName
它的实现可以这样来
Function.prototype.call1 = function(context,...arg){
//将传入的对象保存起来,我们的this指向指向的是context
let newContext = context || window
//给传入的对象添加一个属性保存调用者,这个this就是调用者
newContext.fn = this
//将调用者的执行保存起来
let result = newContext.fn(...arg)
//删除添加的属性
delete newContext.fn
//返回调用执行的结果
return result
}
apply也是类似
Function.prototype.apply1 = function(context,arg){