[英]How to Call a Variable from another Function within the same Object?
I just wish to know if there is a simple way to call a variable from another function within the same Object? 我只想知道是否有一种简单的方法可以从同一Object内的另一个函数调用变量?
var comedy = {
schadenfreude: function() {
var number = prompt("Provide me a number.");
},
irony: function() {
this.schadenfreude();
for(i = 0; i < this.schadenfreude.number(); i++){
return i;
}
}
};
console.log(comedy.irony());
In this example I wish to grab the var number
from the schadenfreude function
and use that prompted number in my for loop with the irony function
. 在此示例中,我希望从
schadenfreude function
获取var number
,并在irony function
for循环中使用该提示号。 Thanks for the help. 谢谢您的帮助。
The "number" variable in your "schadenfreude" function is local to that function. “ schadenfreude”函数中的“ number”变量是该函数的本地变量。 Even if you could get to it (you can't), it would do you no good.
即使您能够做到(您无法做到),也不会带来任何好处。
What you (probably) want is: 您(可能)想要的是:
var comedy = {
number: 0,
schadenfreude: function() {
this.number = prompt("Provide me a number.");
},
irony: function() {
this.schadenfreude();
for(i = 0; i < this.number; i++){
alert(i);
};
}
};
console.log(comedy.irony());
Alternatively, you could have "schadenfreude" assign the value to a "number" property on the object, so that you'd refer to this.number
in the "irony" function. 或者,您可以让“ schadenfreude”将值分配给对象上的“ number”属性,以便在“ irony”函数中引用
this.number
。 In either case, as I noted in the comment in the code, the fact that your for
loop has that return
statement means that the "irony" function will always return zero if the user gives you any non-negative number, and undefined
otherwise. 在任何一种情况下,正如我在代码的注释中所指出的那样,您的
for
循环具有该return
语句这一事实意味着,如果用户给您任何非负数,则“讽刺”函数将始终返回零,否则undefined
。
It sounds like you want to grab a local variable from another member defined on the same object. 听起来您想从定义在同一对象上的另一个成员中获取局部变量。 That's not directly possible.
这不是直接可能的。 Local variables are scoped to the defining function / member and there isn't a way to access them directly.
局部变量的作用域是定义函数/成员,无法直接访问它们。 The function must explicitly return them to the caller in some manner for them to be accessed
该函数必须以某种方式将它们显式返回给调用方,以便对其进行访问
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.