鍍金池/ 問答/HTML/ 被這個this指向弄暈了,求請教

被這個this指向弄暈了,求請教

    function Router(){
        this.routes = {};
        this.currentUrl = '';
    }
    Router.prototype.route = function(path, callback){
        this.routes[path] = callback || function(){};
    }
    Router.prototype.refresh = function(){
        this.currentUrl = location.hash.slice('1') || '/';
        this.routes[this.currentUrl]();
    }
    Router.prototype.init = function () {
        window.addEventListener('load', this.refresh.bind(this), false);
        window.addEventListener('hashchange', this.refresh.bind(this), false);
    }
    window.Router = new Router();
    window.Router.init();

    var content = document.querySelector('body');
    // change Page anything
    function changeBgColor(color) {
        content.style.backgroundColor = color;
    }
    Router.route('/', function () {
        changeBgColor('red') 
    })
    Router.route('/blue', function () {
        changeBgColor('blue') 
    })
    Router.route('/green', function () {
        changeBgColor('green') 
    })
    
    
    
    

問題就在于 window.addEventListener('load', this.refresh.bind(this), false);
這句話中 this.refresh.bind(this),弄暈了, 換成this.refresh.apply(this)和 call 都會報錯, 有人能幫我來理清這個this指向的順序嗎?以及為什么不能使用 apply和call

回答
編輯回答
毀憶

this.refresh.apply(this)
是改變作用域并執(zhí)行
this.refresh.bind(this)
是改變作用域并返回新函數(shù)(未執(zhí)行)
這里的this.refresh.bind(this)是改變addEventListener的this將其指向Router,因為事件的this指向事件的綁定者,這里是window

2018年8月26日 07:21
編輯回答
夢若殤

apply,call改變函數(shù)中this的指向,就相當(dāng)于給對象添加了一個屬性,
而bind它改變函數(shù)中this的指向,是創(chuàng)建了一個函數(shù),內(nèi)部實現(xiàn)了apply的作用,但是它返回的是個函數(shù),你可以在addEventListener中當(dāng)回調(diào)函數(shù)使用,而前者沒有這個作用,所以會報錯。

2018年3月21日 08:54
編輯回答
未命名

call和apply會自動執(zhí)行函數(shù),而bind不會

window.addEventListener里的第二個參數(shù)是一個函數(shù)

用call和apply的話得到的就是執(zhí)行完的結(jié)果,也就是函數(shù)返回值,你的refresh沒有返回值(return),得到的也就是undefined,所以會報錯啦

2017年8月1日 10:12