1

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");
2
  • 6
    The console.log line is after the return statement. It won't execute. Commented Dec 30, 2014 at 22:36
  • Since you are defining toString method as a prototype method, it becomes an instance property of the created object. It means that after creating a person with var person = x.newPerson(1, "John"); you can use it like person.toString(). Also this.Id should be this.id in toString definition. Commented Dec 30, 2014 at 22:42

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.