2017-02-20 152 views
2

這裏是我做了測試的例子:是一個全局範圍的函數內的JavaScript函數?

function f1(var1){ 
    alert('f1 called'); 
    function f2(var2){ 
    alert('f2 called'); 

    } 
    this.data='something else'; 
    this.f2 = f2; 
} 
f1.data='something'; 
f1.f3 = function(var3){ 
    alert('f3 called'); 
} 
console.log(f1); //shows the function 
console.log(f1.data); //can have properties attached - cool 
console.log(f1.f2(2)); //error: "f1.f2" is not a function 
console.log(f1.f3(3)); //this works as expected 

看來,F1裏面的功能f2在範圍上本地。是否有任何等效的方法來調用這樣的函數內的函數?

+1

其分配是這樣的: 'this.f2 = function(){// ...'! –

+3

您需要將其暴露給全局範圍,例如,使用任何一種JS模塊模式。但是,在本地確定一個功能的關鍵在於*避免*污染全球範圍。你最終的目標是什麼? –

+4

@ibrahimmahrir \t ...這就是'this.f2 = f2'所能做的;沒有區別。 –

回答

7

不幸的是,this必然的window全球範圍內,因爲你還沒有使用實例new f1();

var f = new f1(); 
f.f2(); // Now works 
0

取決於你想達到什麼樣的一個實例f1,有一對夫婦的模式你可以用來訪問f1以外的f2功能。您可以使用new實例化一個f1對象:

function f1() { 
    this.f2 = function() { console.log('f2'); } 
} 

new f1().f2() //logs 'f2' 

或者你也可以從功能f1返回功能f2

function f1() { 
    return function f2() { console.log('f2'); } 
} 

f1()() //logs 'f2' 
0

變化代碼:

function f1 (var1){ 
    alert('f1 called');   
}; 
f1.data='something else'; 
f1.f2 = function f2(var2){ 
    alert('f2 called'); 
};