Hi all, my goal is to create a sort of "Javascript library," if you could call it that. I'm intending to use it to just manipulate pages as I browse the web, dynamically loading it as a greasemonkey script. The idea is to have "win
" get mapped to window
, "doc
" -> document
, "win.loc
" -> win.location
, and a few other convenience mappings, but you get the idea. Can you just give me a few examples for me to pick up the syntax from, and I'll extrapolate the rest? Thanks so much.
views:
145answers:
2Just assign variables like so:
var win = window;
var doc = document;
You can't assign win.loc
without modifying the window
object in this case though. Also, the window object is special because after assigning win
, you'll be able to get it with win.win
or win.win.win
and so on (window
is the global object.)
In any case, you can still assign loc
to the window
object:
win.loc = window.location;
// Can now be referenced as:
loc; // (window is the global object)
win.loc;
win.location;
window.location;
Now that is how to do what you're asking for. Most likely you shouldn't do this. Normally, frameworks are defined to use up only one global variable, with a suitable name:
var Blixt = (function () {
var localVariable = 123;
return {
loc: window.location,
myFunc: function () {
alert(localVariable);
}
};
})();
All this is pretty complex stuff if you're not familiar with JavaScript though, so it's not a good project to start with if you're new to JavaScript.
NOTE:This is really a request for clarification of Blixt's answer above, which would not fit into one comment.
Ok, thanks - this is a pretty good answer. I'd just like to make some clarifications to it:
If I define the aliases using the syntax you've given above,
win.loc
will behave exactly the same aswindow.location
without any exceptions? (Just making sure)I followed most of it, but the part with the
Blixt
function I did not understand. What is the expected behavior/result of defining this function?I am kinda new to JS, but why is this not a good idea? What negative consequences could it possibly have? I'm just looking to do things like
C-l javascript:win.loc=doc.ref<ENTER>
for a tab that was opened by CTRL-clicking a link in another tab, nothing too complex.Speaking of which, and I have a feeling that this might be different from browser to browser, but is there any possible way for me define a
js:
URI scheme and map it to thejavascript:
one? Thanks for the great answer.