文章目录
1 问题
看不太明白bind(this)的写法
Router.prototype.refresh = function () {
console.log('触发一次 hashchange,hash 值为', location.hash);
this.currentUrl = location.hash.slice(1) || '/';
this.routes[this.currentUrl]();
};
Router.prototype.init = function () {
window.addEventListener('hashchange', this.refresh.bind(this), false);
};
window.Router = new Router();
window.Router.init();
2 bind(this)的作用
- 传递上下文
refresh方法中,有关键字this,调用相关代码,内部的this指向的调用者,所以如果不使用bind(this) , 事件触发后,window调用 refresh后,refresh方法中的this将指向window.
- bind(this),this参数,就是指定上下文,方法内部的this都将是传入的这个对象
init方法执行时, 当前的this是Router,因此bind(this)后,window调用refresh方法后,方法内部的this对象即为传入的参数Router对象
3 总结
- window接收的方法,可能理解为,只是一个方法体,任何对象都可以调用,因此如果方法体中存在 this, 绑定上下文是有必要的