[英]javascript: access all variables of a parent function
I decided to create a funcB
function that I call from funcA
. 我决定创建一个
funcB
函数,该函数从funcA
调用。 I want all variables from funcA to be available in the funcB so func B can change that variables. 我希望funcA中的所有变量都可以在funcB中使用,以便func B可以更改该变量。 How to modify the code below so it meets my requirements?
如何修改下面的代码,使其符合我的要求? I doubt passing all variables it the only possible and the best way.
我怀疑传递所有变量是唯一可行且最佳的方法。
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
keyword refers to obj
object this
关键字引用obj
对象
You can define object with properties and methods inside it. 您可以在对象内部定义属性和方法。 With methods all the variables can be manipulated as you wish, from this example with
fnB
I'm changing values of properties which are displayed from fnA
method 使用方法,可以根据需要对所有变量进行操作,在使用
fnB
示例中,我正在更改通过fnA
方法显示的属性的值
One way is to drop the var
keyword: 一种方法是删除
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();
}
This will expose them to the global scope so funcB
can access them. 这会将它们公开给全局范围,以便
funcB
可以访问它们。 Notice you can also create the varaibles in the global scope itself, with the var
keyword, but both methods will ultimately have the same effect. 注意,您也可以使用
var
关键字在全局范围内创建变量,但是两种方法最终都将具有相同的效果。
Note: 注意:
var1
or var20
in the global scope. var1
或var20
,则此方法可能无法工作。 In such case, it will modify the global value and may result in unwanted errors. This is not possible as when you declare a variable with the var
keyword, they are scoped
to the function in which they are declared. 这是不可能的,因为当您使用
var
关键字声明变量时,它们的scoped
于声明它们的函数。
If you avoid the var
keyword, they are instead defined as a global variable
. 如果您避免使用
var
关键字,则将它们定义为global variable
。 This is deemed very bad practice. 这被认为是非常不好的做法。
I would recommend you read up on javascript coding patterns , particularly the module pattern. 我建议您阅读javascript编码模式 ,尤其是模块模式。
For example: 例如:
var myNamespace = (function () {
var foo, bar;
return {
func1: function() {
foo = "baz";
console.log(foo);
},
func2: function (input) {
foo = input;
console.log(foo);
}
};
})();
Usage: 用法:
myNamespace.func1();
// "baz"
myNamespace.func2("hello");
// "hello"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.