对象内部的this指向问题

1.

const obj2 = {
    fn: () => {
        console.log(this);
    }
}
obj2.fn(); // window 


上面代码中箭头函数没有自己的this,向上找this对象(在对象大括号中没有作用域?),所以最终指向window。

2.

const obj2 = {
    fn: function() {
        console.log(this); // obj2
    }
};
obj2.fn();


上述代码fn函数被obj2对象调用,this指向obj2

二、对象中的函数返回一个函数
1.

const obj2 = {
    fn: function() {
        console.log("1", this);
        return function() {
            console.log("2", this);
        }
    }
}
obj2.fn()(); // 1 obj2 2 window


上述代码fn返回一个函数这个函数没有明显被谁调用,那就是被window调用了。

2.

const obj2 = {
   fn: function() {
       console.log("1", this);
       return () => {
           console.log("2", this);
       }
   }
}
obj2.fn()(); // 1 obj2 2 obj2


上述代码fn返回一个箭头函数,虽然没有明确调用者,但是这里箭头函数可能涉及到往上一层作用域中搜索this,上一层作用域就是fn函数的作用域,因为被obj2调用,因此this指向obj2。

三、函数中有立即执行函数
1.

const obj2 = {
   fn: function() {
       console.log("1", this);
       (function() {
           console.log("2", this);
       })();
       return () => {
           console.log("3", this);
       }
   }
}
obj2.fn()(); // 1 obj2 2 window 3 obj2

这里,执行了一个立即执行函数,没有明确的调用者,this指向window。

2.

const obj2 = {
   fn: function() {
       console.log("1", this);
       (() => {
           console.log("2", this);
       })();
       return () => {
           console.log("3", this);
       }
   }
}
obj2.fn()(); // 1 obj2 2 obj2 3 obj2


这里跟上面例子基本相同,只不过这里立即执行函数是箭头函数,箭头函数向上一层作用域中查找this,于是找到了fn中的this,

四、有定时器的情况
1.

const obj2 = {
    fn: function() {
        console.log("1", this);
        (() => {
            console.log("2", this);
        })();
        return () => {
            console.log("3", this);
            setTimeout(() => {
                console.log("4", this);
            }, 0);
        }
    }
}
obj2.fn()(); // 1 obj2 2 obj2 3 obj2 4 obj2

这里的定时器回调函数是箭头函数,还是涉及到向上一级作用域搜索this。

2.

const obj2 = {
    fn: function() {
        console.log("1", this);
        (() => {
            console.log("2", this);
        })();
        return () => {
            console.log("3", this);
            setTimeout(function() {
                console.log("4", this);
            }, 0);
        }
    }
}
obj2.fn()(); // 1 obj2 2 obj2 3 obj2 4 window

这里的定时器回调函数没有明确调用者,this指向window。

补充关于箭头函数中arguments问题
在箭头函数中,和this相似arguments也指向上一层函数中的arguments。

function f1(x, y) {
    return (z) => {
        console.log(arguments);
    }
}

const tempFn = f1(1, 2);
tempFn(3);
/*
[Arguments] { '0': 1, '1': 2 }

猜你喜欢

转载自blog.csdn.net/znhyXYG/article/details/126172003