我决定创建一个funcB
函数,我从funcA
调用。我希望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();
}
答案 0 :(得分:2)
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
方法
答案 1 :(得分:1)
一种方法是删除var
关键字:
function funcB(){
alert(var1);//how to make it alert 5
alert(var20);//how to make it alert 50
}
function funcA(){
var1 = 5;
var20 = 50;
funcB();
}
这会将它们暴露给全局范围,以便funcB
可以访问它们。请注意,您还可以使用var
关键字在全局范围内创建变量,但这两种方法最终都会产生相同的效果。
注意:
var1
或var20
,则此功能可能无效。在这种情况下,它将修改全局值并可能导致不必要的错误。 答案 2 :(得分:1)
这是不可能的,因为当您使用var
关键字声明变量时,它们对于声明它们的函数是scoped
。
如果您避开var
关键字,则会将其定义为global variable
。这被认为是非常糟糕的做法。
我建议您阅读javascript coding patterns,特别是模块模式。
例如:
var myNamespace = (function () {
var foo, bar;
return {
func1: function() {
foo = "baz";
console.log(foo);
},
func2: function (input) {
foo = input;
console.log(foo);
}
};
})();
用法:
myNamespace.func1();
// "baz"
myNamespace.func2("hello");
// "hello"