Javascript Domain Model Object Convention

If I need to create a domain model object in C #, I can do something like this:

public class Person { Public string Name { get; set; } Public string Gender { get; set; } Public int Age { get; set; } } 

In Javascript, what is the convention for defining such objects? I think something like this:

 NAMESPACE.Person = function() { this.name = ""; this.gender = ""; this.age = 0; } 
+4
source share
2 answers

Yes, spot basically. The only thing you need to add is that you must prototype methods . As you prototype the situation in design, I usually prefer to do it inside the class, but it is labeled so that it runs only when necessary, and only once.

 NAMESPACE.Person = function() { this.name = ""; this.gender = ""; this.age = 0; if(!NAMESPACE.Person._prototyped) { NAMESPACE.Person.prototype.MethodA = function () {}; NAMESPACE.Person.prototype.MethodB = function () {}; NAMESPACE.Person.prototype.MethodC = function () {}; NAMESPACE.Person._prototyped = true; } } 

Explaining why: the reason for this is performance and inheritance. Prototyped properties are directly related to the object of the class (function), and not to the instance, therefore they are available only for reference to the function. And since they are in the class, only one object must exist, not one instance.

+3
source

I don’t think that most of the “agreement” exists, but you can declare the variables “private”, and Crockford shows you how here

 function Constructor(...) { var that = this; var membername = value; function membername(...) {...} } 

Note. Function operator

 function membername(...) {...} 

is short for

 var membername = function membername(...) {...}; 

To complete the answer, you will do it, you will notice that I do it a little differently

 // class function Person() { // private variable var name = "Default Value"; // getter this.getName = function() { return name; } // setter this.setName = function(s) { name = s; } } // instanciate an object var p = new Person(); // alerts: Default Value alert(p.getName()); p.setName("def"); // alerts: def alert(p.getName()); // alerts: undefined alert(p.name); 
0
source

All Articles