-1

I have read over some rules to determine what the value of this is in different scenarios in Javascript. All was well till the example below threw me off.

function Person(name){
  this.name = name; //this is the object when function used as constructor (as expected)
  this.changeName = someFunction(); // produces error

  function someFunction(){
    this.nickName = this.name+"by"; //this is now the global object and not the instance, thus the name property does not exist.

  }
}

var a = new Person ('bob'); //error due to the function in changeName property.

From what I understood, the this variable takes up the value of the invoking object when called through dot notation or takes up the value of the newly constructed function when used with the new key word.

Can someone explain why the this statement in the function above is the global objet and not the newly instantiated object?

alaboudi
  • 3,187
  • 4
  • 29
  • 47

2 Answers2

1

Can someone explain why the this statement in the function above is the global objet and not the newly instantiated object?

Because when you call a(n unbound) function as func(), this will refer to the global object (or undefined if the function is in strict mode).

Every function (except arrow functions) has its own this value. So the fact that you are calling Person as new Person() and that this inside Person refers to a new object, doesn't have any impact on the this value in someFunction. It only matters how you can someFunction.

You could call someFunction and explicitly set its this value via .call:

this.changeName = someFunction.call(this);

See also: How to access the correct `this` inside a callback?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • It answers why my implementation is incorrect. Thank you. I have already used the call() function in my fix when I realized it was the global object inside, but I needed a reason to know why it was the global object. This is the explanation I was looking for (Y). – alaboudi Jan 05 '17 at 20:59
0

The this within someFunction() will reference a global object, because it's inside a function call. See a fuller, much more complete explanation at How does "this" keyword work within a function?

If you wish to solve the issue, alias this inside the parent.

function Person(name){
  var self = this;  // Store a reference to the current instance  
  self.name = name; 

  self.changeName = someFunction(); // Odd that you'd capture the return value of a setter, ...

  function someFunction(){
    self.nickName = self.name+"by"; //self references the instance, creating the property.

  }
}
Community
  • 1
  • 1
alttag
  • 1,163
  • 2
  • 11
  • 29