Javascript 从外部函数访问属性
我正在尝试设置一个功能,如下所示Javascript 从外部函数访问属性,javascript,Javascript,我正在尝试设置一个功能,如下所示 function Class() { } Class.prototype.func = function(f) { var hello = "hello"; setTimeout(f, 1000); }; new Class().func(function() { alert(hello); }); 我希望f()函数能够访问hello变量。问题是f()没有在func()函数的上下文中运行 我试过使用var hello=“hello”
function Class() {
}
Class.prototype.func = function(f) {
var hello = "hello";
setTimeout(f, 1000);
};
new Class().func(function() {
alert(hello);
});
我希望f()
函数能够访问hello变量。问题是f()
没有在func()
函数的上下文中运行
我试过使用var hello=“hello”
和this.hello=“hello”代码>但两者都不起作用
f()
如何访问hello
?它不能。变量根本不存在于定义函数的范围内
您需要将其暴露在更大的范围内(例如,通过使其成为类
对象的实例的属性或全局属性)。鉴于您得到的代码结构,任何传递到“func”中的“f”都无法访问“hello”
但是,您可以这样做:
Class.prototype.func=function(f){
this.hello="hello";
setTimeout(f.bind(this),1000);
};
new Class().func(function(){
alert(this.hello);
});
JavaScript作用域基于函数(声明上下文)之间的词法关系。使用var
声明的变量可用于声明该变量的函数以及该函数中声明/实例化的所有函数。在您的例子中,匿名函数不是在“func”中声明的,因此“func”的局部变量永远都不可见。也无法从“func”内部动态公开本地范围。(在回答这样的问题时,我通常会忘记忽略eval()
,但在这里,我认为即使是eval()
也无法解决这种情况。)将其作为参数传递
function Class(){
}
Class.prototype.func=function(f){
var hello="hello";
setTimeout(function(){
f(hello)
},1000);
};
new Class().func(function(hello){
alert(hello);
});
您需要传递一个参数。完美:当我可以时,D将标记为答案。我从来不知道bind
方法。@Bob“bind”方法在较新的浏览器中可用,您可以在MDN网站上找到一些。