Search code examples
javascriptclassmethodsthisself

javascript: explanation needed for this piece of code


Who can explain me this code (alert "Hi! My name is Mark" appears):

function Person(name) {
    var self = this;
    this.name = name;

    function person(){
        alert("Hi! My name is "+self.name);
    }
    return {person:person};
}

new Person("Mark").person();

and why I don't see alert if return {person:person}; is removed? What person:person is here?

Also, why this.name (not self.name) is undefined in function person(){}?


Solution

  • The main problem is that you should not return {person:person}, but you should not specify a return or "return this;".

    new Person("Mark") will create an instance of Person, but the function Person returns the {person:person}. Inside {person:person} the right one(value) is the method. var x = new Person("Mark") will return {person: function person(){alert("Hi...")}. x.person() will show the alert.