我正在尝试获取 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/