【发布时间】: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();
为什么?
【问题讨论】:
-
Object.create不是替代new!调用构造函数有什么问题? -
@Bergi 我认为它们几乎相同,只是我读过一些文章说创建实例时应该使用“Object.create”,而不是使用“new”。我想我会坚持使用 var c1 = new this.MyChild();
-
搞砸那些文章。不需要初始化的时候可以使用
Object.create,不能初始化的时候应该使用。也许看看stackoverflow.com/a/11253826/1048572、stackoverflow.com/a/14267886/1048572 或stackoverflow.com/q/10898786/1048572
标签: javascript jquery oop