2016-02-29 43 views
0

我有一個js庫文件,其變量我不想直接提供給其他文件。例如:如何爲這個簡單的場景實現封裝?

我的第一個文件名爲lib.js如下:

lib.js

var foo = 90; 

function printFoo(){ 
    console.log(foo) 
} 

在下面這就要求lib.js第二個文件,我想printFoo()工作正常,但我也想直接訪問lib.js中的變量foo被阻止。我怎樣才能做到這一點?

<script src="lib.js"></script> 
<script> 
    console.log(foo);// I don't want foo of lib.js being accessible here 

    printFoo();// but i want this line to display the value of foo from lib.js 
</script> 
+1

顯示函數模式?一個簡單的IIFE? – Bergi

回答

0

因爲我知道你想在lib.js 所以

function printFoo(){ 
var foo = 90; 
return function(){ 
    console.log(foo) 
} 
} 

只有入店FOO的HTML將

<script src="lib.js"></script> 
<script> 
    console.log(foo);// here foo is undefined 

    var Foo = printFoo(); 
Foo()// here console .logo of foo 90 
// but i want this line to display the value of foo from lib.js 
</script> 

現在foo是根據FOO()範圍,所以訪問的方式是封裝printFoo函數

相關問題