2014-01-15 18 views
0

創建一個對象內部對象比方說,我有以下代碼:不能使用的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(); 

爲什麼?

+1

'Object.create'不*代替'new'!調用構造函數有什麼問題? – Bergi

+0

@Bergi我認爲他們幾乎是一樣的,這只是我讀過一些文章說創建實例時應該使用「Object.create」,而不是使用「new」。我想我會堅持使用var c1 = new this.MyChild(); – Josh

+0

擰這些物品。當你不需要初始化時,你可以使用'Object.create',並且當你不使用初始化時你應該使用它。也許看看http://stackoverflow.com/a/11253826/1048572,http://stackoverflow.com/a/14267886/1048572或http://stackoverflow.com/q/10898786/1048572 – Bergi

回答

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()創建的對象之間共享。

+0

你改變了什麼? –

+0

@cookiemonster:將構造函數轉化爲適合的東西。 +1 – Bergi

+0

@Bergi:是的,我現在看到它。我專注於第一個'init'。雖然構造函數沒有改變。 –

1

我認爲你應該使用的

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

代替

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

不過,它那麼就不會有'init'方法。 – Bergi

相關問題