【问题标题】:Why is this Object.create() prototype object not accessing the properties of the Constructor object? [duplicate]为什么这个 Object.create() 原型对象不访问 Constructor 对象的属性? [复制]
【发布时间】: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


【解决方案1】:

Object.create 确实创建了一个空对象,并且不调用构造函数方法对其进行初始化。

您想使用new 运算符。这就是它的目的。

【讨论】:

    【解决方案2】:

    因为在第一种情况下,您创建的对象没有 items 数组

    【讨论】:

      【解决方案3】:

      您正在通过Object.create() 创建对象并引用该构造函数的原型。当你这样做时,构造函数本身永远不会被调用。 Object.create() 不是魔法;你传给它一个对象,这就是它使用的对象。您从构造函数传递原型对象,这是一个非常好的对象,但没有什么会导致构造函数本身被调用。

      【讨论】:

        猜你喜欢
        • 2021-09-19
        • 2012-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-04
        • 2019-02-10
        • 2015-01-18
        • 1970-01-01
        相关资源
        最近更新 更多