我正在尝试封装一些代码来获取并释放 Firefox 扩展中选项卡的 onLoad 事件,以便根据需要,我调用:
var onLoad = new MyHandler_onLoad();
然后当我完成后,我打电话:
onLoad.unregister();
原则上,这段代码可以很好地实现上述功能,直到您深入研究更具体的细节为止。
function bind(scope, fn) {
return function(){
fn.apply(scope, arguments);
};
function MyHandler_onLoad()
{
this.scan = function() {
do_scan(this.browser); // this.browser == undefined
};
this.register = function() {
this.tab.addEventListener("load", this.scan, false);
};
this.unregister = function() {
this.tab.removeEventListener("load", this.scan, false);
};
this.tab = gBrowser.selectedTab;
this.browser = gBrowser.selectedBrowser;
this.register();
window.addEventListener("unload", bind(this, this.unregister), false);
};
由于 JavaScript 的 this
的行为,我很挣扎。我希望能够通过我的扫描功能访问 this.browser,但不能。
我使用bind
来确保unregister
在unload
上获得适当的上下文。但是,我无法通过调用 scan
来执行此操作,因为如果我没有名称,以后将无法将其删除。
在 JavaScript 中是否有一个好的模式来执行此类操作?
我尝试将bind(this, this.scan) 的结果存储为构造函数中的变量,但它没有帮助,现在正在努力寻找选项。
最佳答案
this
,在 JavaScript 中,始终指向当前对象。如果没有当前对象,this
指向 window
,它始终是顶级范围(无论如何在浏览器中)
举例:
function(){
...
this.foo = function(){
this;
// There is no object here, so `this` points to `window`
}
}
<小时/>
function foo(){
this;
// again, no object so `this` points to window`
}
foo();
<小时/>
function foo(){
this;
// because initialized with `new`, `this` points to an instance of `foo`
this.bar = function(){
this;
// no object, `this` points to `window`
}
}
var foobar = new foo();
// above is roughly equivalent to: foo.apply({}, arguments); Note the new object
foobar.bar();
<小时/>
var foo = {
bar : function(){
this;
// `this` points at `foo` -- note the object literal
}
};
<小时/>
function foo(){
}
foo.prototype.bar = function(){
this;
// `this` points to the instance of `foo`
}
var foobar = new foo();
foobar.bar();
<小时/>
绑定(bind)的概念允许您将 this
变量锁定为您想要的任何内容,因为对函数的最终调用是通过 .apply(scope, params )
,所以回到你原来的问题,我上面的最后一个例子可以工作,所以这个:
function foo(){
this.scan = bind(this, function(){
this;
// `this` points to instance of `foo` IF `foo` is instantiated
// with `new` keyword.
});
}
new foo()
如果您想更多地了解所有这些,我有两篇我很久以前写的文章应该会有所帮助:
http://www.htmlgoodies.com/primers/jsp/article.php/3600451/Javascript-Basics-Part-8.htm http://www.htmlgoodies.com/primers/jsp/article.php/3606701/Javascript-Basics-Part-9.htm
关于javascript - JavaScript 事件处理程序中处理 'this' 的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5772527/