最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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*/};
发布评论

评论列表(0)

  1. 暂无评论