Constructors in the module template

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

Why is it not like this work, is it complete and complete 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());
+5
source share
3 answers

You need to derive a method and attach it to the Person prototype. But when you do this, you will have a name property and a name method that will not work, so consider renaming the latter

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

OR, you can simply attach it to thisand make getName a privileged method:

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

. name() , , , . getName :

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/

+3

var function foo() {} ( , "" function foo() {} ), . , .

, ( ), this ( self, self = this):

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

, name, . name , , . :.

var name = "john";

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

All Articles