by tkiley · 15y ago · 0 comments
One quibble: In the "common pitfalls" section regarding the "this" object, they say that locally-defined functions within other functions never have any practical use. I might disagree: with a little coaxing, you can convince locally variables inside the constructor (both functions and other variables) to serve as private properties of an object; this is the only technique I know that allows for private properties.
(I haven't actually done this in code that has been maintained/used anywhere, I just did it as an experiment and filed it away as a "that's cool" for future reference)
Edit: Here is an example of what I'm talking about: https://gist.github.com/866103
Might also come in handy if you are into functional programming with Javascript.
Since all functions are objects in JS, you can create a function with some internal (private) functions and properties than return a object with some publicly accessible functions. A basic example:
https://gist.github.com/866343
Closure gives you a really powerful structure that lets you encapsulate your code and then you don't have to use this and risk clobbering the global window object :)
1. If you use the "new" keyword, and don't execute the function. "x = new foo()". X becomes an "object". "foo()" is behaving like a class. You got to define the properties and methods of this class with the "this" keyword. Once you create your object with the "new" keyword, these variables got assigned to the object. And better, you can access them with the prototype.
2. If you execute the function in your code, that is you put "foo()": Open your FireFox with FireBug and notice two new global variables in the Windows object "get_my_private" and "set_my_private".
So it depends on the usage. "this" insides of a function is useful, if your intent is to use the function as a class. If not, it's dangerous, as the variables becomes global and may interfere with other variables.
function Foo(){
if (this == window) throw "USE NEW!";
// continue with object creation
}
Or use the standard practice of having class-creating function names capitalized, and let people know to follow it. function Podcast() {
if(false === (this instanceof Podcast)) {
return new Podcast();
}
// other code
}