Search code examples
javascriptthisecmascript-5

JavaScript, constructor and "this"


There's something I don't understand with "this" keyword, more precisely when there is no "this". like this example :

function Person(name) {
    this.name=name;
    this.go = function() {
        console.log("My name is " + name);
    }
}

let person = new Person("Peter");
person.go();

My problem is when I call go() on person object. Why does it work ?? I thought I needed to put "this.name" inside my method. Because when I run person.go(), inside the go() method : name is not a parameter, is not a local variable and not a global variable either. How the JS engine manages to understand what "name" means ?

For example when I do that :

var person = {
   name: "Peter",
   go: function() {console.log("My name is " + name);}
};

person.go() doesn't work because "name" is unknown and I have to add this.name to make it work.

I don't understand why it works in the first example but not the second one.

Thanks


Solution

  • Your code works without this. because the go function has captured the name parameter from the constructor function in the surrounding scope. Your code is equivalent to:

    function Person(xyz) {
        this.name=xyz;
        this.go = function() {
            console.log("My name is " + xyz);
        }
    }
    

    IE you're not actually making use of the name property of your Person object.