rogermushroom
rogermushroom

Reputation: 5586

Constructors in the Module Pattern

When using the module pattern in javascript how should constructors be defined, if at all. I would like my constructor to fit into a standard module pattern and not be global.

Why doesn't something like this work, is it complete and total nonsense?

var HOUSE = function() {
    return {
        Person: function() {
            var self = this;
            self.name = "john";
            function name() {
                return self.name;
            }
        }
    };
}();

var me = new HOUSE.Person();
alert(me.name());

Upvotes: 5

Views: 1933

Answers (3)

Adam Rackis
Adam Rackis

Reputation: 83358

You need to bring the method out, and attach it to the Person prototype. But when you do, you'll have a name property, and a name method, which won't work, so consider renaming the latter

HOUSE.Person.prototype.getName = function(){
    return this.name;
}

OR, you could just attach it to this, and make getName a privileged method:

  Person: function() {
        this.name = "john";
        this.getName = function() {
            return this.name;
        }
    }

Upvotes: 1

Richard Dalton
Richard Dalton

Reputation: 35793

Your code is almost fine. However the function name() was not public but the variable was so you were trying to execute the variable causing an error. Add the function getName onto the object and call that instead:

var HOUSE = function() {
    return {
        Person: function() {
            var self = this;
            self.name = "john";
            self.getName = function() {
                return self.name;
            }
        }
    };
}();

var me = new HOUSE.Person();
alert(me.getName());

http://jsfiddle.net/8nSbP/

Upvotes: 3

pimvdb
pimvdb

Reputation: 154828

Using var and function foo() {} (the latter as a declaration, which means "just" function foo() {} without assigning it), create local symbols. So, the function is not available outside the constructor.

Whatever you want to expose (make public), you should assign to this (or self since you defined self = this):

self.getName = function() {
    return self.name;
};

Note that you already used name, so I gave function another name. If you wanted to make the name string local, and expose the function, then they can have the same name since there is no conflict. E.g.:

var name = "john";

self.name = function() {
    return name;
};

Upvotes: 2

Related Questions