JavaScript中的嵌套类 [英] Nested class in JavaScript

查看:450
本文介绍了JavaScript中的嵌套类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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();

能请你帮我吗?

推荐答案

如果您想将函数嵌套在函数中-可以,但是您应该学习javascript语法,词汇范围和变量提升的工作原理以及总体-阅读道格拉斯·克罗克福德的文章(或观看他的视频) 。

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

这篇关于JavaScript中的嵌套类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆