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 23 hours agomyApp.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 23 hours agoPerson
object. Why it could be an issue if I define my qualified class name asmyApp.model.Person
? – CK Lee 23 hours agoPerson
object, you need to assign them to the rootPerson
object definition. I'm not sure if this would count as an instance. Most likely, it'd be only to thePerson
objects that belong tomyApp.model
objects. So if you havePerson
somewhere else, then those objects won't have those functions on them. – krillgar 22 hours ago