0

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;
}
user8783104
  • 175
  • 2
  • 11
  • 1
    Why do you think it would? `obj` is just an object (even if this was a called as a method on an instance, `this` would still not reference `obj`). You should read up on the this keyword for a basic understanding. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this – rgthree Nov 12 '17 at 19:34
  • see: https://stackoverflow.com/help/someone-answers – c0der Nov 25 '17 at 17:59

1 Answers1

1

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
dhilt
  • 13,532
  • 6
  • 48
  • 67