Reputation: 19
I am learning design patterns in javascript but I have a problem creating a module. I am creating a Person object inside of module and I have combined it with a constructor pattern, just beacuse I am learning it too, but nothing happens.
Can anybody help me, I don't undertand my mistake here
var myModule = (function () {
function Person(id, name) {
this.id = id;
this.name = name;
}
Person.prototype.toString = function () {
return "\nID: " + this.Id + "\nName: " + this.name;
};
return {
newPerson: function (id, name) {
return new Person(id,name);
console.log(Person.toString());
}
};
})();
var x = myModule;
x.newPerson(1, "John");
Upvotes: 1
Views: 587
Reputation: 26139
You should use
var myModule = (function () {
function Person(id, name) {
this.id = id;
this.name = name;
}
return {
newPerson: function (id, name) {
return new Person(id,name);
}
};
})();
var x = myModule;
console.log(x.newPerson(1, "John"));
Forget the toString()
, most consoles can fetch the object, and display it in a much better way.
In your case you want to log the toString()
of the Person
constructor, which would result a string something like this:
"function Person(id, name) {
this.id = id;
this.name = name;
}"
but it does not run, because you put it after the return statement in the newPerson()
function, and the return statement stops execution and returns with the results.
Upvotes: 1