我决定创建一个从 funcA
调用的 funcB
函数。我希望 funcA 中的所有变量在 funcB 中可用,以便 func B 可以更改这些变量。
如何修改下面的代码以满足我的要求?我怀疑通过它传递所有变量是唯一可能和最好的方法。
function funcB(){
alert(var1);//how to make it alert 5
alert(var20);//how to make it alert 50
}
function funcA(){
var var1=5;
...
var var20=50;
funcB();
}
最佳答案
var obj = {
one : "A",
two : "B",
fnA : function() {
this.fnB(); // without fnB method result will be displayed as A B, with fnB as C D
console.log(this.one + " " + this.two);
},
fnB : function() {
this.one = "C";
this.two = "D";
}
};
obj.fnA();
this
关键字引用obj
对象
您可以在其中定义带有属性和方法的对象。使用方法,所有变量都可以按照您的意愿进行操作,从这个示例中使用 fnB
我正在更改从 fnA
方法显示的属性值
关于javascript:访问父函数的所有变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22508542/