微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我最近一直在使用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();

虽然我真的很喜欢这种语法我永远不会真正使用它,因为没有办法在dog对象里面的任何函数中引用动物实例.所以我想出了这个符号作为替代品

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

虽然现在我可以从狗功能的所有子功能内部访问动物实例,但我并不喜欢我已经完成它的轻微hacky方式.
有人有任何清洁方法吗?

最佳答案
也许你正在寻找这样的东西……

这将允许您具有以下语法
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(){
            }
        }
    }
}

原文地址:https://www.jb51.cc/js/429624.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐