【问题标题】:can't use Object.create to create object inside an object in javascript不能使用 Object.create 在 javascript 中的对象内创建对象
【发布时间】:2014-01-15 19:10:54
【问题描述】:

假设我有以下代码:

(function($) {
    var Obj = {
        init: function() {
            var c1 = Object.create(this.MyChild);
            var c2 = Object.create(this.MyChild);
            c1.init(); //not working!!!
        },
        MyChild: function() {
            this.init = function() {
                console.log('calling MyChild init function');   
            }
        }
    };

    Obj.init();
})(jQuery);

在创建 Obj 时,我使用了对象字面量,因为我不需要创建它的实例,而在创建 MyChild 对象时,我使用了构造函数并使用了 Object.create,因为我需要创建多个 MyChild 实例。

但是,当我调用 Object.create 时,它​​不起作用,当调用 c1.init() 时,它说 init 函数未定义,但如果我将 Object.create(this.MyChild) 替换为:

var c1 = new this.MyChild(); 
c1.init();

为什么?

【问题讨论】:

标签: javascript jquery oop


【解决方案1】:

Object.create(func)new func() 做的事情不同!

Object.create() 创建一个(否则为空!)对象,该对象的原型将设置为该对象,然后传递给该函数 (MDN)

要在您的示例中使用Object.create(),您可以像这样修改它:

(function($) {
    var Obj = {
        init: function() {
            var c1 = Object.create(this.MyChild);
            var c2 = Object.create(this.MyChild);
            c1.init(); //not working!!!
        },
        MyChild: {
            init: function() {
                console.log('calling MyChild init function');   
            }
        }
    };

    Obj.init();
})(jQuery);

但在这种情况下,一切都将指向您的 MyChild 对象。 MyChild 的属性将在您使用 Object.create() 创建的每个对象之间共享。

【讨论】:

  • @cookiemonster:把构造函数改成这里合适的。 +1
  • @Bergi:是的,我现在看到了。我专注于第一个init。虽然构造函数没有改变。
【解决方案2】:

我认为你应该使用

var c1 = Object.create(this.MyChild.prototype);

而不是

var c1 = Object.create(this.MyChild);

【讨论】:

  • 仍然没有init 方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-13
相关资源
最近更新 更多