-3
var func=function(){console.log(that)}
var obj = {
    foo(){
        var that=this;
        var a=func;
        a();
    }
}   

obj.foo();

Result :

Uncaught ReferenceError: that is not defined

Siddharth
  • 505
  • 2
  • 4
  • 9

3 Answers3

0

that only exists inside foo because that's where it's declared. Your func function is outside of foo, so the that variable doesn't exist there.

If you want to be able to access it in both places, you can declare it outside both functions:

var that;
var func=function(){console.log(that)}
var obj = {
    foo(){
        that=this;  // <-- no  var
        var a=func;
        a();
    }
}   

obj.foo();
JLRishe
  • 99,490
  • 19
  • 131
  • 169
0

Because JavaScript uses lexical scoping, not dynamic scoping. That means variables aren't looked up in calling scopes at runtime. Only the nesting structure of the source code matters.

melpomene
  • 84,125
  • 8
  • 85
  • 148
0

You don't have a reference to that in func. Either declare that as a global variable or pass it as an parameter to func.

Option 1: Passing that as a parameter

var func = function(that) {
  console.log(that)
}
var obj = {
  foo() {
    var that = this;
    var a = func(that);
    //invoke function a like this;
    a;
  }
}

obj.foo();

Option 2: Declare that as a global variable

var that;

var func = function() {
  console.log(that)
}
var obj = {
  foo() {
    that = this;
    var a = func(that);
    //invoke function a like this;
    a;
  }
}

obj.foo();
Pugazh
  • 9,453
  • 5
  • 33
  • 54