HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

JavaScript constructor and namespace in object literal style

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
javascriptliteralstyleconstructorandobjectnamespace

Problem

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.

Solution

I would suggest splitting the addition of the methods as follows:

myApp.model.Person.prototype.sayName = function () {
    alert(this.name);
};

myApp.model.Person.prototype.sayHi = function () {
    alert("Hi, " + this.name);
};


This way you can define additional methods in different places (if needed), as you're not replacing the entire prototype in one go.

Code Snippets

myApp.model.Person.prototype.sayName = function () {
    alert(this.name);
};

myApp.model.Person.prototype.sayHi = function () {
    alert("Hi, " + this.name);
};

Context

StackExchange Code Review Q#62402, answer score: 4

Revisions (0)

No revisions yet.