-4

I wrote a contrived script that illustrates what I don't understand:

var newObject = {}
newObject.testAttribute = "I'm newObject";
newObject.someMethod = function(){
    console.log(this.testAttribute);
    var sub_function = function(){

        console.log(this.testAttribute);   
    }
    sub_function();
}
newObject.someMethod();

In the sub_function, I expected "this" to refer to the object newObject because of closure, but the output on the console is

"I'm newObject"
undefined
Shayan Ghosh
  • 862
  • 6
  • 14

1 Answers1

0

this represents a context. Every function has its own context unless you directly specify it, e.g.

this.myfunction = function(){}

or

myfunction.bind(this)

you can learn more here

smnbbrv
  • 19,108
  • 9
  • 62
  • 100