lundi 29 février 2016

How to implement encapsulation for this simple scenario?

I have a js lib file whose variable I don't want to be directly available to other files. Example:

My first file called lib.js is as follows :

lib.js

var foo = 90;

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

In the second file below which calls lib.js, I want printFoo() work fine but I also want direct access to variable foo from lib.js being prevented. How can I do that?

<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>

Aucun commentaire:

Enregistrer un commentaire