【问题标题】:In the following javascript code, why variable that is not accessible to func function? [duplicate]在以下 javascript 代码中,为什么 func 函数无法访问变量? [复制]
【发布时间】:2016-12-19 09:07:05
【问题描述】:
var func=function(){console.log(that)}
var obj = {
foo(){
var that=this;
var a=func;
a();
}
}
obj.foo();
结果:
Uncaught ReferenceError: that is not defined
【问题讨论】:
标签:
javascript
function
scope
【解决方案1】:
that 只存在于foo 中,因为它是在其中声明的。您的func 函数在foo 之外,因此that 变量在那里不存在。
如果你想在两个地方都可以访问它,你可以在两个函数之外声明它:
var that;
var func=function(){console.log(that)}
var obj = {
foo(){
that=this; // <-- no var
var a=func;
a();
}
}
obj.foo();
【解决方案2】:
因为 JavaScript 使用词法作用域,而不是动态作用域。这意味着在运行时调用范围时不会查找变量。只有源代码的嵌套结构很重要。
【解决方案3】:
您在 func 中没有对 that 的引用。要么将其声明为全局变量,要么将其作为参数传递给func。
选项1:将that作为参数传递
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();
选项2:将that声明为全局变量
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();