this指向的几种情况
普通Function调用的this指向
myFun()
function myFun(){
console.log(this) //window
}
对象中方法中this指向
let obj = {
name:'zjq',
age:"18",
habby(){
console.log(this.name,this)
}
}
obj.habby() //指向obj
构造函数中的this指向
function A(name, age){
this.name= name;
this.age = age;
this.habby = function(){
console.log(this.name,this.age,this) //指向实例化之后的对象
}
}
let Ac = new A('zjq',18)
Ac.habby()
箭头函数的this指向
const A = () => {
console.log(this)
}
let obj = {
name: 'zjq',
age: "18",
A,
B(){
console.log(this,'B')
}
}
console.log(obj.A()) //window
console.log(obj.B()) //obj
普通函数我们都知道是谁调用指向谁,是在调用的时候确定的,但是箭头函数指向外层作用域,但是obj身上没有this这个变量,直到最外层window,跟着作用域往上找了
简单实现改变this指向的三种方法
call
Function.prototype.mySelfCall = function (obj, ...arrList) {
obj = obj ? Object(obj) : window
let that = this; //前边的函数
obj.fn = that;
obj.fn(...arrList)
delete obj.fn
}
apply
Function.prototype.mySelfApply = function (obj, arrList) {
obj = obj ? Object(obj) : window
let that = this; //前边的函数
obj.fn = that;
obj.fn(...arrList)
delete obj.fn
}
bind
Function.prototype.mySelfBind = function (obj, ...arrList) {
obj = obj ? Object(obj) : window
let that = this; //前边的函数
obj.fn = that;
return () => {
obj.fn.mySelfCall(obj, ...arrList); delete obj.fn }
}
测试
function A(name, age) {
this.name = name;
this.age = age;
this.habby = function (...num) {
console.log(this.name, this.age, this, ...num) //指向实例化之后的对象
}
}
let Ac = new A('zjq', 18)
Ac.habby.mySelfCall({
name: 111, age: 222 }, 1, 2, 3, 4)
Ac.habby.mySelfApply({
name: 333, age: 444 }, [1, 2, 3, 4, 5, 6, 7, 8])
Ac.habby.mySelfBind({
name: 555, age: 666 }, 1, 2, 3, 4)()