Open JesseZhao1990 opened 6 years ago
掌握了this的绑定规则之后,来思考一下。如何实现一个bind函数?
Function.prototype.bind = function(content){
let that = this;
let arg = Array.prototype.slice.call(arguments,1);
return function(){
let thisArg = arg.concat([...arguments]);
that.apply(content,thisArg)
}
}
function Person(name,age,sex){
console.log(this.name)
console.log(name)
console.log(this.age)
console.log(age)
console.log(this.sex)
console.log(sex)
}
var person1 = {
name:'zhangsan',
age:22,
sex:'male'
}
Person = Person.bind(person1,'lisi')
Person(80,'female')
如果要判断一个运行中函数的this绑定,就需要找到这个函数的直接调用位置,找到之后就可以顺序应用下面的这四条规则来判断this的绑定对象
ES6中的箭头函数并不会使用四条标准的绑定规则,而是根据当前的词法作用域来决定this,具体来说,箭头函数会继承完成函数调用的this绑定。