oop - Object oriented programming with Javascript - Constructors - Stack Overflow

I've seen a lot of this...function myObject(data) {var myData = data;}myObject.prototype.doSometh

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.

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.

Share Improve this question asked May 12, 2009 at 1:41 Matt DoakMatt Doak
Add a ment  | 

2 Answers 2

Reset to default 4

Take a look at:

  • Private Members in JavaScript
  • Prototypal Inheritance in JavaScript
  • Classical Inheritance in JavaScript

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745141151a4613436.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信