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

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

function createNewPerson(name) {
    var obj = {}; = 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(; // Hello
      console.log(name); // World
    var obj = {}; = '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) { = name;
    var salva = new createNewPerson('Salva');
    console.log(; // Salva