Hacker News new | past | comments | ask | show | jobs | submit login

Be careful of that. There is a trap right there. Your example is using the "new" keyword and not executing the function. So what happened?

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.




There's an easy way to fix that, though:

  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.


Fix: ( from http://elegantcode.com/2010/12/21/basic-javascript-part-4-en... )

    function Podcast() {
      if(false === (this instanceof Podcast)) {
        return new Podcast();
      }
      // other code
    }




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: