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, 绑定上下文是有必要的
本文详细探讨了JavaScript中`bind(this)`的用途,解释了为何在事件监听器中使用它来确保上下文正确。当在全局环境中调用方法时,不使用bind(this)会导致方法内的this指向window。通过bind(this),可以固定方法的上下文,确保this始终指向Router对象。总结指出,在处理包含this的方法时,明确上下文绑定对于防止混淆至关重要。
3748

被折叠的 条评论
为什么被折叠?



