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
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
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();
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.
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();