Matt Doak
Matt Doak

Reputation:

Object oriented programming with Javascript - Constructors

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.

Upvotes: 2

Views: 3574

Answers (2)

Sasha Chedygov
Sasha Chedygov

Reputation: 130967

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*/};

Upvotes: 3

Related Questions