Later today, I was scrolling through ejhon.com slides and I found out the following:
Give this code
function katana () {
this.myvar = true;
}
katana ();
console.info (myvar);
Past the moment I compiled the code, I thought that myvar is attached to the katana function. Actually, it gets attached to the window objects, which pollutes the global namespace.
I returned to my projects, which all uses the same approach.. a little bit differently
function katana () {
this.myvar = true;
}
var xyz = new katana();
console.info (myvar);
I have a function object and instead of executing the function, I just create a new instance of it (I’m not actually quite sure what’s happening). I then use xyz to store values and use those values through prototyped methods to do some jobs.
What surprised me is when I did some debugging with FireBug is that xyz is not existent. There is no variables attached to window object. Why?
I did some more debugging and the xyz object is attached to window > object, but in the DOM it’s not apparent and has no traces. There is also something new in the debugging window, a node called ‘scopechain’ with a call and that has the values of the xyz object.
Okay, what’s happening underneath? Is that a good method that I should stick with or shall I look for an alternative?
I have looked at some questions and answers, I’m mainly looking for what this method do in the background.
When you say
new katana(), Javascript calls thekatanafunction, with a new blank object asthis. Once it returns, presumably initialized, the new object (or whateverkatanareturns, as long as it’s an object) is set up so that its ‘prototype’ (the object that it’ll inherit fields and such from) is the same as thekatanafunction’s prototype.Yeah, that didn’t make much sense either the first time i went through it. The oversimplified version is, you say
new katana(), and Javascript creates what’ll be akatanainstance and lets thekatanafunction initialize it. You saykatana(), andthisis basically the last object in the call stack to have been used in an instance method call. (If your caller wasx.foo,this == x.) If there’s no such object, seemsthisis the same aswindow.As for why
xyzisn’t showing up, you declared the variable withvar. That changes the scope. If you got rid of that, you’d see awindow.xyz.