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());
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:
this
Person: function() { this.name = "john"; this.getName = function() { return this.name; } }
. name() , , , . getName :
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/
var function foo() {} ( , "" function foo() {} ), . , .
var
function foo() {}
, ( ), this ( self, self = this):
self
self = this
self.getName = function() { return self.name; };
, name, . name , , . :.
name
var name = "john"; self.name = function() { return name; };