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?