If I were to make a new function using the Function constructor, how could I give it a non-temporary scope to access besides window (meaning the scope only has to be evaluated once, not every time the function is called)? The purpose is to construct multiple variables that require some pretty costly calculations, and I don’t want to reconstruct them every time the function is called, but I also don’t want to store them in window. Any ideas?
If I were to make a new function using the Function constructor, how could
Share
For the above described purpose, you use static functions. You cannot prevent scope from being evaluated at every call, because this is the way JavaScript works, but you can speed it up by not having
windowin the scoping chain.Now anywhere in your code, you can call that method by using
namespace.someMethod();. Just be careful. The above is a static method. You can call it without instantiating. But you MUST NOT usethis.propertyinside a static function. It is a potentially very dangerous operation, as it may give an extension access to the global object and basically un-restricted permissions.And the above is a static JavaScript method. It does not have window in the scoping chain.
Here’s how to create a constructor using the same pattern. When you want to use a constructor, you always instantiate before using. For that you have the
newkeyword.Now anywhere in your code you can do:
You have successufully created an instance of your
namespace.coordinateclass. Using the pattern I gave you, you can replicate almost the entire functionality of Java or C or any other Object Oriented language.