mitch said on 27/04/2006 2:35 AM AEST:
> Is there a way to reassign a function? I tried this:
>
> function func() { alert("func"); }
> function func2() { alert("func2"); }
>
> function testFunc() {
> document.func = func2;
> func();
> }
>
> and it prints "func" not "func2". I'd like to be able to override the
> global function "func" to make it do something else. Is there a
> trick to do it? Thanks.
>
> The reason I want to do it is for unit testing. I have some test
> code I'm writing, and I want to call the production code and override
> some of the functions in the production code, making other
> functions unit-testable. I would prefer to do it without changing
> the production code.
In addition to other responses, functions declared in the global scope
belong to the global object. In browsers, the global object is
synonymous with the window object.
However, not all user agents are browsers and therefore may not have a
window object. To be confident of explicitly addressing global objects
and properties, you may want to create your own reference to the global
object (usually at the beginning of the script):
var _global = this;
Now you can use:
function testFunc() {
_global.func = _global.func2;
_global.func();
}
In some situations that may be good practice, but usually:
function testFunc() {
func = func2;
func();
}
will do.
--
Rob
Group FAQ: <URL:http://www.jibbering.com/FAQ>
|