2014-03-19 27 views
1

我決定創建一個funcB函數,我從funcA調用。我希望funcA中的所有變量都可以在funcB中使用,所以func B可以更改這些變量。 如何修改以下代碼,使其符合我的要求?我懷疑所有變量都是唯一可能的和最好的方法。javascript:訪問父函數的所有變量

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(); 
} 
+1

JavaScript變數作用範圍只在定義的功能 – thefourtheye

+0

這應該這樣做:http://jsfiddle.net/lshettyl/7Murm / – lshettyl

回答

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方法顯示的屬性值操作,從這個例子

JSFiddle

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關鍵字創建變量,但兩種方法最終都會產生相同的效果。

注:

  1. 如果已經有在全球範圍var1var20這可能無法正常工作。在這種情況下,它將修改全局值並可能導致不需要的錯誤。
  2. ,此方法是首選的官方代碼,是不好的做法Reason
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"