AntonBoarf
AntonBoarf

Reputation: 1313

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

Upvotes: 0

Views: 65

Answers (2)

James Thorpe
James Thorpe

Reputation: 32202

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.

Upvotes: 3

Tsvetan Ganev
Tsvetan Ganev

Reputation: 8826

In the first case, the name value comes from the function argument name. The go method uses the argument's value, instead of the this context.

In the second case, name is undefined in the go method. You need to provide a context (this.name) in order to access it.

Upvotes: 1

Related Questions