1. this指向
1.1 全局环境
全局执行环境中,指向全局对象;
1.2 函数内部
1)直接调用:
①指向全局对象(非严格模式下)
②指向undefined(严格模式下)
2)对象方法调用
2. 改变this指向
2.1调用时指定
1)call 调用;2)apply 调用。
2.2 创建时指定
1)bind方法;2)箭头函数。
3. 手写call、apply、bind方法
3.1手写call方法:
Function.prototype.myCall = function(thisArg,...args) {
const key = Symbol('key') //生成唯一key,避免函数名称与thisArg中的函数重复
thisArg[key] = this //由于func调用的myCall,所以this指向func
const res = thisArg[key](...args)
delete thisArg[key]
return res
}
const person = {
name:'huihui'
}
const func = function(a,b) {
console.log(this) //person
console.log(a,b) //1,2
return a+b
}
const res = func.myCall(person,1,2)
console.log(res) //3
3.2手写apply方法
Function.prototype.myApply = function(thisArg,args) {
const key = Symbol('key') //生成唯一key,避免函数名称与thisArg中的函数重复
thisArg[key] = this //由于func调用的myApply,所以this指向func
const res = thisArg[key](...args)
delete thisArg[key]
return res
}
const person = {
name:'灰灰'
}
const func = function(a,b) {
console.log(this) //person
console.log(a,b) //1,2
return a+b
}
const res = func.myApply(person,[1,2])
console.log(res) //3
3.3手写bind方法
Function.prototype.myBind = function(thisArg,...args) {
return (...resArgs) => this.call(thisArg,...args,...resArgs)
}
const person = {
name:'xiao灰'
}
const func = function(a,b) {
console.log(this) //person
console.log(a,b) //1,2
return a+b
}
const func1 = func.myBind(person,1)
const res = func1(2)
console.log(res)//3