創建一個對象內部對象比方說,我有以下代碼:不能使用的Object.create在JavaScript
(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
@Bergi我認爲他們幾乎是一樣的,這只是我讀過一些文章說創建實例時應該使用「Object.create」,而不是使用「new」。我想我會堅持使用var c1 = new this.MyChild(); – Josh
擰這些物品。當你不需要初始化時,你可以使用'Object.create',並且當你不使用初始化時你應該使用它。也許看看http://stackoverflow.com/a/11253826/1048572,http://stackoverflow.com/a/14267886/1048572或http://stackoverflow.com/q/10898786/1048572 – Bergi