Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can function references be executed properly (1)?

Tags:

javascript

win points to window. NS is a temporary namespace for this post. I thought that if I wanted access to setTimeout, I could just copy over the function reference as such:

NS.setTimeout = win.setTimeout;

However, execution will throw an error:

NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object @ ...

To fix this error, I just did:

NS.setTimeout = function (arg1, arg2) {
    return win.setTimeout(arg1, arg2);
};

However, I don't know why this fixed it. I don't know what language mechanics are causing this behavior.

like image 882
nativist.bill.cutting Avatar asked Jul 25 '13 13:07

nativist.bill.cutting


2 Answers

What you want is this :

NS.setTimeout = win.setTimeout.bind(win);

or what you already do, if you want to be compatible with IE8.

Because setTimeout, like many window functions, needs the receiver (this) to be window.

Another IE8 compatible solution, more elegant in my opinion than yours (because it doesn't use the fact you know the number of arguments needed by setTimeout), would be

NS.setTimeout = function(){
  return win.setTimeout.apply(win, arguments);
};
like image 51
Denys Séguret Avatar answered Oct 13 '22 00:10

Denys Séguret


The reason why you can't do that is because, when assigining, you're changeing the call context of setTimeout, which isn't allowed.
Nor is it allowed for setInterval, and many of the other native objects/functions. Again: a great rule of thumb: if you don't own the object, don't touch it. Since functions are objects in JS, that rule applies to them, too

check the specs on the global object and its properties/builtin funcitons:

There are certain built-in objects available whenever an ECMAScript program begins execution. One, the global object, is part of the lexical environment of the executing program. Others are accessible as initial properties of the global object.

And so on. But the lexical environment is quite significant. By assigning a reference to the function elsewhere, you could well be masking part of the lexical environment, or exposing too much of the global environment (eg mashups).

like image 35
Elias Van Ootegem Avatar answered Oct 13 '22 00:10

Elias Van Ootegem