Catalin
Catalin

Reputation: 11721

Combine javascript closures together

I have a "host" javascript closure, in which i keep all the common variables i am using over the website

var hostFunction = (function () {
    var variableA = $("#variableA");
    var variableB = $("#variableB");

    // some usefull code here
} ());

In my website, in another javascript file, i have another closure

var childFunction = (function () {
    var changeValue = function () {
        variableA.html("I was changed");
    };

    // other usefull code
} ());

How is possible to insert "childFunction" inside "hostFunction" so i can get access to those variables?

What is the best practice of sharing variables across the website but also keeping them inside a scope so they don't conflict with other javascript variables?

Upvotes: 0

Views: 240

Answers (2)

Rich O'Kelly
Rich O'Kelly

Reputation: 41757

If any information needs to be shared globally, it is best practice to use namespaces to mitigate the risk of your variables clashing with any others.

This blog post gives a reasonable introduction to namespacing in javascript.

Upvotes: 2

soniiic
soniiic

Reputation: 2685

I think you need the word this for those variables to be seen in other scopes

var hostFunction = (function () {
    this.variableA = $("#variableA");
    this.variableB = $("#variableB");

    // some usefull code here
} ());

You pass in your host in the constructor of your childFunction like this:

var childFunction = (function (myHost) {
    var changeValue = function () {
        myHost.variableA.html("I was changed");
    };

    // other usefull code
} (hostFunction));

Upvotes: 0

Related Questions