javascript在全局对象中使用'this' [英] javascript using 'this' in global object
问题描述
在gloabl对象中使用'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中调用内联脚本page:
Now if we call in an inline script in the HTML page:
SomeGlobalObject.show();
window.setTimeout("Msg.show()", 1000);
一切正常。
但如果我们做类似的事情
But if we do something like
AppendEvent(window, 'load', Msg.show);
我们收到错误,因为从事件范围调用时,this.rendered是未定义的。
we get an error because this.rendered is undefined when called from the event scope.
- 你知道为什么会这样吗?
- 你能否解释一下,如果有另一种更聪明的方法可以做到这一点必须每次将SomeGlobalObject.someProperty重写为SomeGlobalObject代码?
谢谢!
AppendEvent只是一个简单的跨浏览器函数来附加一个事件,代码如下,但是为了回答上述问题并不重要。
AppendEvent is just a simple cross-browser function to append an event, code below, but it does not matter in order to answer the above questions.
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);
}
推荐答案
当你引用一个函数时是一个对象的方法,你将它与该对象分离,这个
将不再是对象的引用。
When you reference a function that is a method of an object, you're detaching it from that object and this
will no longer be a reference to the object.
最简单的解决方案是将其包装在一个匿名函数中:
The easiest solution is to wrap it in an anonymous function:
AppendEvent(window, 'load', function () { Msg.show() } );
还有 bind
方法可用于ECMAScript第5版实现中的函数,允许你这样做:
There's also the bind
method available to functions in ECMAScript 5th Edition implementations, which allow you to do this:
AppendEvent(window, 'load', Msg.show.bind(Msg, arg1, arg2));
JS框架,Prototype,也为当前的JS实现提供了这种方法。代码(感谢@bobince):
The JS framework, Prototype, provides this method to current JS implementations too. The code (thanks @bobince):
// From Prototype.js
if (!Function.prototype.bind) { // check if native implementation available
Function.prototype.bind = function(){
var fn = this, args = Array.prototype.slice.call(arguments),
object = args.shift();
return function(){
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};
}
这篇关于javascript在全局对象中使用'this'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!