Variables in a Javascript module visible outside of it? -
to start, i'm coming .net world, there static classes (c#, known modules in vb) , instance classes - can instantiate.
this question javascript, i'm trying recreate pattern know , make module / static class. here code:
var mymodule = { variable1: 0, variable2: 1, method1: function() { //code goes here }, method2: function() { //mode code goes here }, method3: function() { //and more prove pattern } } method1(); //error - no such method - ok, good, expect variable1 = 5; //silently assigns variable inside mymodule 5 ?
please explain why methods declared inside namespace not visible, variables ? also, there way prevent variables being visible outside of mymodule
, in same script ?
i start trying address misconceptions - module plain javascript object initialised using literal. object not hide information - javascript not have private
, public
scope same way as, java does. furthermore, way access properties of object access them through it
method1();
this fails because trying variable called method1
, execute it. not exist, hence error. can do, however, mymodule.method1()
. because mymodule
actual object. in java, similar having object mymodule = new object()
. can call methods on it, mymodule.tostring()
- "unconventional" thing, instance named capital letter - variables in java , javascript start lower case convention - there no language feature mandates it.
next, there line:
variable1 = 5; //silently assigns variable inside mymodule 5 ?
to answer comment on line - no, doesn't. above line equivalent doing window.variable1 = 5
. have there called "implied global". name self descriptive, clarify window.foo = 42
explicit global foo = 42
implied because falls window
object. however, var foo = 42
not global - var keyword not attach or use global window
object. if use "use strict" directive cause javascript engine throw error when encounters implied global.
now, these misconceptions aside, there minor 1 merely gloss on it's major thing - mymodule.method1
, on functions rather methods. method object oriented terminology subroutine carries implied state, object it's assigned to. function, however, free floating executable code not intrinsically "belong" object. distinction may seem rather academic, has big impact. however, i'll ask trust me on one, broad topic cover here.
so, that's what's wrong. how make right? first, on scopes, needed rest of it:
javascript has 2 scopes - global , functional. here means, exactly:
var foo = 42; function bar(input) { var foo = input; return foo; } console.log(bar(5)); //5 console.log(foo); //42
we have variables called foo
- 1 inside function 1 not. assigning 1 not change other - it's because in different scopes. that's var
keyword - if omitted inside function, accessing same thing
var foo = 42; function bar(input) { foo = input; return foo; } console.log(bar(5)); //5 console.log(foo); //5
this because inner foo
not declared in functional scope, accesses outer (and no outer - window.foo
property).
that's simple enough. however, there hidden aspect here not obvious yet bears mentioning: there only 2 scopes. here mean
function bar(condition) { var foo = 5; if (condition) { var foo = 42; } return foo; } console.log( bar(false) ); //5 console.log( bar(true) ); //42
so, though seemingly declare new foo
property inside if statement that's same 1 first one. other languages have block scope inside { }
so, variables declared there, stay there. not true in javascript. easy miss, it's important note.
now, onto problem. there excellent resources javascript module pattern, mention few: addy osmani's "learning javascript design patterns" book has description, todd motto has, believe is, article beginners while the adequately post goes more in-depth yet it's still accessible. cover module pattern. found many module patterns - in resources , around web. module allows have similar public
, private
other languages. not try explain it, since think other people have done way better can. however, brief explanation module is. again, other resources can cover better.
a module leverages javascript feature called closure more information here , here (one of upvoted stackoverflow questions). remember how said, there 2 scopes in javascript? closure, put simply, provides functional scope. here how looks like:
(function() { /* code goes here */ })()
to dissect briefly have function code enclosed in (/* function goes here */)()
. in effect executes function inside put functional scope. powerful, however, , here example
var closure = (function() { var privatevar = "secret"; return { publicvar: 42, getprivatevar() { return privatevar; } } })() console.log(closure.publicvar); //42 console.log(closure.getprivatevar()); //"secret" //let's change closure.publicvar = 5; closure.privatevar = "changed"; console.log(closure.publicvar); //5 console.log(closure.getprivatevar()); //"secret"
and have (something resembling) private field. again, var privatevar
stay "bottled up" inside function scope , not accessible outside. incidentally, example of module pattern. instead of var closure
have called mymodule
. rather simplistic take on but, here thing - doesn't more complicated. different modules boil down similar things - expose data in different manners. yet, concept similar - "private" fields stay inside, , "public" ones, can access elsewhere.
this long, should cover basics need going.
Comments
Post a Comment