0

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

AntonBoarf
  • 1,239
  • 15
  • 31
  • 1
    "name is [...] not a local variable" - Yes, it is. – str May 24 '18 at 14:30
  • Think of any variables defined outside of a function as globals for any inner functions (within the same {}), and this as a reference to a object (that happens to be a function) – Cody G May 24 '18 at 14:30
  • FYI `name` is not a good identifier to use in client-side code as `name` is also a Global property of the `window` object and can cause bugs later on in the code. – Scott Marcus May 26 '18 at 21:33

2 Answers2

3

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.

James Thorpe
  • 31,411
  • 5
  • 72
  • 93
1

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.

Tsvetan Ganev
  • 8,246
  • 4
  • 26
  • 43