javascript - 在 Javascript 中创建和使用模块

标签 javascript module

我正在尝试获取 Javascript 中的现有对象并将其重写为模块。下面是我尝试重写为模块的代码:

var Queue = {};
Queue.prototype = {
    add: function(x) {
        this.data.push(x);
    },
    remove: function() {
        return this.data.shift();
    }
};
Queue.create = function() {
    var q = Object.create(Queue.prototype);
    q.data = [];
    return q;
};         

这是我制作模块的尝试:

var Queue = (function() {

    var Queue = function() {};

    // prototype
    Queue.prototype = {
        add: function(x) {
            this.data.push(x);
        },
        remove: function() {
            return this.data.shift();
        }
    };

    Queue.create = function() {
        var q = Object.create(Queue.prototype);
        q.data = [];
        return q;
    };


    return Queue;
})();

这是对的吗?如果是,我如何在 js 代码的其他函数或区域中调用它。我感谢所有帮助!

最佳答案

拥有一个空的构造函数,然后使用该构造函数上的属性作为有效的构造函数似乎有点毫无意义。

为什么不直接利用构造函数...

var Queue = (function() {

    var Queue = function() {
        if (!(this instanceof Queue))
            return new Queue();

        this.data = [];
    };

    Queue.prototype = {
        add: function(x) {
            this.data.push(x);
        },
        remove: function() {
            return this.data.shift();
        }
    };

    return Queue;
})();
<小时/>

或者如果您更喜欢使用 Object.create ,我会这样做:

var Queue = (function() {

    var Queue = function() {
        var o = Object.create(proto);

        o.data = [];

        return o;
    };

    var proto = {
        add: function(x) {
            this.data.push(x);
        },
        remove: function() {
            return this.data.shift();
        }
    };

    return Queue;
})();

在这两种情况下,您只需使用 Queue创建新对象。

var q = Queue();

从技术上讲,第一个应该使用 new Queue() ,但它有 instanceof测试允许 new被省略。

关于javascript - 在 Javascript 中创建和使用模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13792570/

相关文章:

javascript - html5/javascript 意味着不能保护源代码?

python - 在 Python 中使用堆栈

node.js - 错误: Incompatible SOCKS protocol version: 71

c - Redis 中 RedisModule_Alloc() 的自动内存管理

node.js - 模块 vs. 依赖 vs. 库 vs. 包 vs. 组件

python - 在 python 中导入模块时会发生什么?

javascript - 十字图像关闭灯箱

javascript - 使用phantomjs检索skyscanner结果的html代码

javascript - 使条件函数更有效

javascript - Grunt.js : how do I normalize files myself, Grunt 的工作方式?