Skip to content Skip to sidebar Skip to footer

Nested Class In Javascript

I'm a totally newbie in JavaScript, which i need for a new project. And now I have a problem: var main = new function() { this.init = new function() { //access somethin

Solution 1:

If you want to nest functions inside function - you CAN, but you should learn javascript syntax, how lexical scope and variable hoisting works, and overall - read Douglas Crockford's articles (or watch his videos).

The code you have shown will not work, try to look at my modification of it, and understand the difference.

varMain = function() {
    /* this function is a constructor */var m = this; // store scope// do your init stuff

    m.boringCollection = {
        /* simple object with function inside *//* notice JSON style formatting */
        doStuff : function(){
            //do something
        },
        doOtherStuff : function(){
            //do something else         
        };
    };
    m.coolConstructor = function () {
        var cc = this; // store scope             var sleep = true; // just an example variable
        cc.moveMyself = function(){
            //do something          
        };
        cc.init = function() {
            sleep = false; // just an example
            cc.moveMyself(); // will work
            cc.work(); // will FAIL, because function work is defined after its called
        };
        cc.work = function() {
            // do some work
        };
    };        
};

var main = newMain(); // make new instance of Main 
main.boringCollection.doOtherStuff(); // will work

main.coolConstructor.init(); // will NOT work var scrappy = new main.coolConstructor(); // make new instance of m.coolConstructor
scrappy.init(); // will work

Solution 2:

JavaScript doesn't have classes out of the box. You need to implement classes yourself.

One popular implementation is JS.Class, if you don't want to write your own implementation.

Post a Comment for "Nested Class In Javascript"