[英]Why does this inner function return undefined?
I do this 我做这个
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.
and 和
function myFunction() {
var myVar = "I think I am encapsulated";
function getMyVar() {
return myVar;
}
}
var myProperty = myFunction();
myProperty.getMyVar(); // tells me myProperty is undefined
and even 乃至
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. 因为这对我来说很直观。
Thanks 谢谢
What you did is just define a function inside myFunction
, creating a closure ... 您所做的只是在myFunction
内定义一个函数,创建一个闭包...
To remedy the implementation, make getMyVar
an instance member : 要纠正该实现, getMyVar
为实例成员 :
function myFunction() {
var myVar = "I think I am encapsulated";
this.getMyVar = function () {
return myVar;
}
}
You aren't exposing the getMyVar function. 您没有公开getMyVar函数。
You want: 你要:
function myFunction() {
var myVar = "I think I am encapsulated";
this.getMyVar = function() {
return myVar;
}
}
However, myVar is also locally scoped to the function execution... and the funciton hasn't been executed. 但是,myVar还在本地范围内执行函数...并且功能尚未执行。
The last lines need to be 最后几行需要
(new myFunction()).getMyVar();
EDIT: Though perhaps all you're looking for is pseudo-namespacing? 编辑:虽然也许您正在寻找的只是伪命名空间? In which case you can do: 在这种情况下,您可以执行以下操作:
var myObject = {
myProperty: "value",
myFunction: function() { }
}
Or, more likely you're trying to make myVar act like a private member, in which case you can do: 或者,您更有可能尝试使myVar扮演私人会员的角色,在这种情况下,您可以执行以下操作:
var myObject = function() {
var myVar = "I think I am encapsulated";
return {
getMyVar: function() {
return myVar;
}
}
}(); //self-executing function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.