gpt4 book ai didi

javascript - 在其他方法中访问在一个方法中创建的变量

转载 作者:搜寻专家 更新时间:2023-11-01 05:04:15 24 4
gpt4 key购买 nike

我一遍又一遍地为同一个话题发疯,变量范围。对此创建一个全局变量没有用,我尝试在一个函数中返回值以使用另一个函数,但总是在控制台中返回“未定义”错误。这是代码的简单标记:

domElement.plugin({
method1: function() {
// create variable
var myvar = 1;
// other things going on here in this method
},
method2: function() {
// use variable
console.log(myvar);
}
});

这是一个 jquery 插件,我试图在其中访问在 method2 中的 method1(并且是变量)中创建的 var myvar 的值。我在论坛上发现了一些东西,但似乎无法使它们中的任何一个工作,因此非常感谢任何帮助。

最佳答案

您需要使两种方法都可以访问变量范围:

domElement.plugin({
myvar: null,
method1: function() {
this.myvar = 1;
},
method2: function() {
console.log(this.myvar); // = null or 1 depending on when you call this function
}
});

或者您可以将它从一种方法传递给另一种方法:

domElement.plugin({
method1: function() {
var myvar = 1;
this.method2(myvar);
},
method2: function(v) {
console.log(v); // = 1
}
});

我个人会使用第一个示例。

关于javascript - 在其他方法中访问在一个方法中创建的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35414452/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com