【发布时间】:2010-03-30 13:35:50
【问题描述】:
'this'关键字在全局对象中使用时指的是什么?
假设我们有:
var SomeGlobalObject =
{
rendered: true,
show: function()
{
/*
I should use 'SomeGlobalObject.rendered' below, otherwise it
won't work when called from event scope.
But it works when called from timer scope!!
How can this be?
*/
if(this.rendered)
alert("hello");
}
}
现在,如果我们在 HTML 页面中调用内联脚本:
SomeGlobalObject.show();
window.setTimeout("SomeGlobalObject.show()", 1000);
一切正常。
但如果我们这样做:
AppendEvent(window, 'load', SomeGlobalObject.show);
我们得到一个错误,因为this.rendered 在从事件范围调用时未定义。
- 你知道为什么会这样吗?
- 您能否解释一下是否有另一种更智能的方法来执行此操作,而不必每次都将“SomeGlobalObject.someProperty”重写到 SomeGlobalObject 代码中?
AppendEvent 只是一个简单的跨浏览器追加事件的函数,代码如下,不过为了回答上面的问题没关系。
function AppendEvent(html_element, event_name, event_function)
{
if(html_element.attachEvent) //IE
return html_element.attachEvent("on" + event_name, event_function);
else
if(html_element.addEventListener) //FF
html_element.addEventListener(event_name, event_function, false);
}
【问题讨论】:
-
啊,JavaScript,您缺少默认方法绑定已导致其第 100 万个受害者...
标签: javascript object this dom-events