Is this a good way to create a class with a constructor and namespace in object literal style?
// root namespace
var myApp = myApp || {};
// sub namespace
myApp.model = {
// Constructor
Person: function (name) {
this.name = name;
}
};
myApp.model.Person.prototype = {
sayName: function () {
alert(this.name);
},
sayHi: function () {
alert("Hi, " + this.name);
}
};
var p1 = new myApp.model.Person("CK");
p1.sayName();
p1.sayHi();
JSHint shows no error and the full source code is here.
myApp.model.Person.prototype
only add those functions to thePerson
objects that are a part of yourmyApp.model
, and not allPerson
objects? If that is intended, that's fine. I could just see that becoming an issue later on. Do you have a separatePerson
object? – krillgar Sep 9 at 13:05myApp.model
as my package, the fully qualified class name I want to make ismyApp.model.Person
. This class shall have a constructor that take Stringname
as parameter, and have 2 methodssayName
andsayHi
. It is simple to be achieved in Java, but I am not sure how to make it right in Javascript. – CK Lee Sep 9 at 13:15Person
object. Why it could be an issue if I define my qualified class name asmyApp.model.Person
? – CK Lee Sep 9 at 13:59Person
constructor is stored, whether it'smyApp.model.Person
or anywhere else. AllPerson
instances which share that constructor will have access to the functions attached to the constructor'sprototype
. – Cory 22 hours ago