views:

421

answers:

2

I've seen a lot of this...

function myObject(data) {
       var myData = data;
}

myObject.prototype.doSomething = function () {
      alert("I did something!");
}

but the intellisense on Visual Studio gives me a .constructor for functions, which would lead me to believe this would be correct...

function myObject() {
     var myData;

     this.constructor = function(data) {
         myData = data;
     }

     this.doSomething = function() {
         alert("I did something!");
     }
}

I like the encapsulation of the second method, but almost everyone uses the ".prototype". Is there any reason for doing this in particular or is it ok to encapsulate all the classes methods like this.

+2  A: 

That's not at all what constructor does. It simply returns the function. So in your case, it would return myObject. For example:

function someObject() {
  this.a = 5;
}
var obj = new someObject();
obj.constructor; // Would return someObject

See this for more details on the constructor property.

The point of using prototype is that you can extend constructors after they've been created. So you could use it to, for example, add a method to all String objects.

String.prototype.myFunc = function(){/*Some code*/};
musicfreak
+3  A: 

Take a look at:

roosteronacid
You might also want to have a look at http://dean.edwards.name/weblog/2006/03/base/
Ian Oxley