Ernest L
Ernest L

Reputation: 19

Create objects inside a module javascript

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

Answers (1)

inf3rno
inf3rno

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

Related Questions