javascript - 单击后如何将函数返回值分配给变量以供以后在javascript中使用?
问题描述
所以,我想要的是将函数返回值保存在一个变量上以供以后使用,例如,只是为了保存它,但是在单击之后,比如说在一个按钮上。例如,我们有:
let x = 3;
function foo(){
let z = 5;
z = x + 3;
return z;
}
现在,如果我写:
let hold = foo();
它将保留返回值,但我希望在单击后将其保存在“保持”状态,方法是使用以下内容:
document.getElementById("empty_field").onclick = function() {foo()};
在这里,点击调用了函数,但它并没有将返回值保存在任何地方。如何将其保存在变量中?
解决方案
简短的回答:你不能
hold
长答案:您可以通过在设置值之前简单地声明来利用范围的概念。这就是它的样子。
let x = 3;
let hold; //variable is declared here so the click function has access to it.
function foo(){
let z = 5;
z = x + 3;
return z;
}
document.getElementById("empty_field").onclick = function() {
hold = foo()
};
更长的答案:您可以hold
在声明变量的范围内访问或修改任何位置。让我们添加另一个我们hold
再次修改的函数。
let x = 3;
let hold; //variable is declared here so the click function has access to it.
function foo(){
let z = 5;
z = x + 3;
return z;
}
document.getElementById("empty_field").onclick = function() {
hold = foo()
};
document.getElementById("increment").onclick = function(){
hold++; //this the same as hold = hold + 1
}
这也是有效的,因为这些点击函数是在与定义相同的范围内hold
定义的。最好避免使用全局范围的变量。因此,您可以考虑使用构造函数并将对象作为参数在函数之间传递,就像这样......
function myConstructor(){
//initialize
this.hold = 0
this.foo = function(x){
let z = 5;
z = x + 3;
this.hold = z;
}
this.increment = function(){
this.hold++;
}
}
let x = 3;
let myObj = new myConstructor() //I know my naming sucks just bear with me lol
document.getElementById("empty_field").onclick = function() {
myObj.foo(x) //x is still available since it was declared globally
console.log(myObj.hold);
};
document.getElementById("increment").onclick = function(){
myObj.increment();
console.log(myObj.hold);
}
无论如何,这就是它的长短。与往常一样,做事的方法有很多很多,而且没有绝对正确的方法。我只是认为了解一些选项可能会有所帮助。更多关于构造函数的阅读可以在这里完成:https ://www.w3schools.com/js/js_object_constructors.asp
推荐阅读
- azure - Azure VNet ip 到 Kubernetes 入口控制器
- amazon-web-services - 将标签动态应用到 AWS CloudFormation 堆栈
- r - facet_wrap 是否需要最少数量的值?
- angular - Angular防止多次调用服务
- php - maker-bundle 自定义骨架(symfony 4)
- python-3.x - Pandas `.to_pydatetime()` 在 DataFrame 中不起作用
- mysql - 将 postgre 函数迁移到 mysql:检索日期范围
- c# - 打印预览缺少字段
- rollupjs - OpenLayers 6 和 RollupJS 配方
- java - 解析 findBy 中的嵌套对象属性