【发布时间】:2016-02-02 06:08:37
【问题描述】:
例如:
var Queue = function() {
this.items = [];
};
Queue.prototype.enqueue = function(obj) {
this.items.push(obj);
};
var queue = Object.create(Queue.prototype);
queue.enqueue('src');
返回:
Uncaught TypeError: Cannot read property 'push' of undefined(…)
然而,
var queue = new Queue();
queue.enqueue('src');
完全按照我想要的方式工作。我在变量实例化中缺少调用 Object.create() 的关键要素吗?或者 Object.create() 方法是否需要另一种模式来分配要传递给其原型对象的数组?
有人可以向我解释一下这个小细节吗,因为我有必要理解为什么它似乎在我在网上找到的其他示例中有效,除了我自己的.. 非常感谢!
【问题讨论】:
-
Object.create 不会像
Queue那样调用构造函数new
标签: javascript class prototype new-operator