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 Answers 2

4

Take a look at:

Sign up to request clarification or add additional context in comments.

1 Comment

You might also want to have a look at dean.edwards.name/weblog/2006/03/base
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.