为什么此内部函数返回未定义? [英] Why does this inner function return undefined?
问题描述
我这样做
function myFunction() {
var myVar = "I think I am encapsulated";
function getMyVar() {
return myVar;
}
}
var myProperty = myFunction;
myProperty.getMyVar(); // tells me myProperty.getMyVar is not a function.
和
function myFunction() {
var myVar = "I think I am encapsulated";
function getMyVar() {
return myVar;
}
}
var myProperty = myFunction();
myProperty.getMyVar(); // tells me myProperty is undefined
甚至
function MyFunction() {
var myVar = "I think I am encapsulated";
function getMyVar() {
return myVar;
}
}
var myProperty = new MyFunction();
myProperty.getMyVar(); // tells me myProperty.getMyVar is not a function.
在所有这三种情况下,我都会遇到问题.我在所有三个部分中均已将该问题作为在线注释中的内容.现在,在有人告诉我只使用闭包之前,我并没有试图了解闭包,而是试图确切地了解内部函数会发生什么.
and in all three cases I get problems. I have included the problem as in line comment in all three sections. Now, before someone tells me to just use a closure, I am not trying to understand closures, I am trying to understand exactly what happens with inner functions.
如果您能在上面解释,我将不胜感激.因为这对我来说很直观.
If you can explain above, I would grateful. Because it is counter intuitive to me.
谢谢
推荐答案
您所做的只是在 myFunction
内部定义一个函数,创建一个闭包...
What you did is just define a function inside myFunction
, creating a closure ...
要补救该实现,请将 getMyVar
设置为 实例成员 :
To remedy the implementation, make getMyVar
an instance member:
function myFunction() {
var myVar = "I think I am encapsulated";
this.getMyVar = function () {
return myVar;
}
}
这篇关于为什么此内部函数返回未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!