在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/HTML/ 被這個(gè)this指向弄暈了,求請(qǐng)教

被這個(gè)this指向弄暈了,求請(qǐng)教

    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') 
    })
    
    
    
    

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

回答
編輯回答
毀憶

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

2018年8月26日 07:21
編輯回答
夢(mèng)若殤

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

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

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

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

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

2017年8月1日 10:12