Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

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 something.init();
    };
    this.something = new function () {
        this.init = function(){
        //do something
        //execute somethingother()
        };
        this.somethingother = function(){
        //do something          
        };
    };
};

main.init();

Can you please help me?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

var Main = 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 = new Main(); // 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...