什么's当前命名空间/类中JavaScript子命名空间/类的语法

What's the syntax for a JavaScript sub namespaces/class inside current namespace/class?

本文关键字:命名空间 JavaScript 语法 类中 什么      更新时间:2023-09-26

我最近一直在使用JavaScript,并创建了一些大型函数集合。我发现需要有子功能,我想将其从主库中分离出来,但仍包含在主库中,但还没有找到足够优雅的方法来实现这一点。

以下是我目前使用的的几个例子

所以我通常像这样设置主库

// Main library
var animals = function(settings){
    // Main library stuff
}

要添加单独封装但仍然是主库一部分的子类/子功能。。。

这是第一个使用对象文字符号的方法

animals.prototype.dogs = {
    addDog: function(){
        // Can only access the dogs object
        var test = this;
    },
    removeDog: function(){}
}
// Usage of the whole thing
var animalsInstance = new animals({a: 1, b: 3});
animalsInstance.dogs.addDog();

虽然我真的很喜欢这个语法,但我永远不会真正使用它,因为在dogs对象中的任何函数中都没有办法引用animals实例。所以我想出了这个符号来代替

animals.prototype.dogs = function(){
    var parent = this;
    return {
        addDog: function(){
            // The animals instance
            var test = parent;
            // The dogs instance
            var test2 = this;
        },
        removeDog: function(){}
    }
}
// Usage
var animalsInstance = new animals({a: 1, b: 3});
animalsInstance.dogs().addDog();

虽然现在我可以从狗功能的所有子功能中访问动物实例,但我真的不喜欢我做这件事的方式。有人有更清洁的方法吗

也许你正在寻找这样的东西。。。

这将允许您使用以下语法tinyFramework.Utilities.Storage.setItem()tinyFramework.Elements.Modals.createModal()

var tinyFramework = {
    Utilities: {
        Storage: {
            setItem: function(){
            //do stuff
            },
            getItem: function(){
            //do stuff
            }
        },
        Helpers: {
        }
    },
    Elements: {
        Modals: {
            createModal: function(){
            },
            closeModal: function(){
            }
        }
    }
}