javascript - why is 'this' not referencing the object? code below

I don't understand why this.name isn't the same as obj.name, basically why in this case this refers to the window object and not the obj object. In the code below, this.name is instantiated after obj.name..

function createNewPerson(name) {
    var obj = {};
    obj.name = name;
    alert(this.name);
    return obj;
}

1 answer

  • answered 2017-11-12 19:33 dhilt

    Per MDN:

    Inside a function, the value of this depends on how the function is called. Since the following code is not in strict mode, and because the value of this is not set by the call, this will default to the global object , which is window in a browser.

    So in your case you have this as the Window object, not the obj. You may get the obj context inside your function via binding it manually, for example:

    function createNewPerson(name) {
      console.log(this.name); // Hello
      console.log(name); // World
    }
    
    var obj = {};
    obj.name = 'Hello';
    var salva = createNewPerson.apply(obj, ['World']); 
    

    But what you really need, as I can understand, is a function cunstructor and instantiating an object via new operator:

    function createNewPerson(name) {
      this.name = name;
    }
    var salva = new createNewPerson('Salva');
    console.log(salva.name); // Salva