Q4.回調函數中的this?

this指向的解釋你可能知道了,但是當在某些場景下還是會誤導你的,比如回調函數中的this。

不信看看下面的例子:

var a = {
    statusArr: [],
    on: function (state) {
        this.statusArr.push(state);
        return a;
    },
    fire() {
        /**
         * 是否將this存起來
         */
       
        //箭頭函數
        // this.statusArr.forEach((state)=>{
        //    console.log(this);//a 對象
        //    this.actionArr[state]();
        // });

        //普通函數
        var self = this;
        this.statusArr.forEach(function (state) {
            console.log(this == global); //node環境  true
            console.log(this == window); //瀏覽器環境 true
            self.actionArr[state]();
        });
        //亦或是 通過bind改變回調函數中this的指向
        this.statusArr.forEach(function (state) {
            console.log(this);
            this.actionArr[state]();
        }.bind(this));
    },
    actionArr: {
        jump: function () { },
        run() { console.log('run !!!') },
        actionArr: {
            jump: function () { },
            run: function () { },
            fire: function () { }
        }
    }
}
a.on('run').fire();

解決問題的辦法:回調函數作爲參數傳過去的。就是普通函數。

誤解:認爲箭頭函數中的this是this.statusArr

 //箭頭函數
        // this.statusArr.forEach((state)=>{
        //    console.log(this);//錯誤猜測:this爲this.statusArr
        //    this.actionArr[state]();
        // });

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章