gpt4 book ai didi

javascript - 无法使用Object.create在javascript中的对象内创建对象

转载 作者:行者123 更新时间:2023-12-02 17:53:40 24 4
gpt4 key购买 nike

假设我有以下代码:

(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();

为什么?

最佳答案

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

Object.create() 创建一个(否则为空!)对象,该对象的原型(prototype)将设置为该对象,并传递给该函数 ( 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() 创建的每个对象之间共享。

关于javascript - 无法使用Object.create在javascript中的对象内创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21146165/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com