2016-11-10 45 views
0

好的,這裏有一些我正在使用atm的代碼。Javascript中的對象和object.prototype之間的區別

我的問題是,我真的不明白對象和對象原型之間的差異。直到現在,我還以爲,如果我創建一個新的對象,例如新的內存,這繼承了我在內存中聲明的所有屬性。但是,在我的代碼中,我需要爲Memory.prototype添加選項。

所以我的核心問題是:是什麼Object.prototype中的對象的屬性和屬性之間的區別?

編輯:在記憶功能中指定: 我登錄this.options。這不起作用,除非我包括Memory.prototype.options = {...}。如果一個新的Memory從Memory中繼承了這些屬性,並且我定義瞭如上面的this.options.availableCards,爲什麼我需要向原型添加選項?

var createMemory = function(){ 
     new Memory({wrapperID: 'memory-game'}); 
     }; 

     var Memory = function (options) { 
     //check for required options 
     if ((options.wrapperID === undefined)){ 
      console.error('ERROR: not all required options given. wrapperID is required!'); 
      return false; 
     } 

     //hardcoded values 
     this.options.availableCards = 22; 
     this.options.cols = 4; 
     this.options.rows = 4; 
     this.options.fliptime = this.options.flipTime || 1; //set default 
     this.options = extend({}, this.options); 
     extend(this.options, options); 
     //this._init(); 
     console.log(this.options); 

     }; 

     // why is this required? 
     Memory.prototype.options = { 
     onGameEnd: function(){ 
      return false; 
     } 
     }; 

     createMemory(); 
+0

什麼是'extend'? –

+0

這是在代碼中聲明的函數,不用擔心 –

回答

0

你忘了在createMemory返回新對象。

其他一些修復以及我不得不發明extend函數,因爲你沒有包括你的。

//Extend function 
 
function extend(a, b) { 
 
    for (var i in b) { 
 
     if (b.hasOwnProperty(i)) { 
 
     a[i] = b[i]; 
 
     } 
 
    } 
 
    return a; 
 
    } 
 
    //Memory class 
 

 
function Memory(options) { 
 
    //check for required options 
 
    if ((options.wrapperID === undefined)) { 
 
    console.error('ERROR: not all requried options given. wrapperID is requried!'); 
 
    return false; 
 
    } // hardcoded values 
 

 
    this.options.availableCards = 22; 
 
    this.options.cols = 4; 
 
    this.options.rows = 4; 
 
    this.options.flipTime = this.options.flipTime || 1; 
 
    this.options = extend({}, this.options); 
 
    extend(this.options, options); 
 
    //this._init(); 
 
}; 
 
Memory.prototype.options = { 
 
    onGameEnd: function() { 
 
    alert("Inherited") 
 
    } 
 
}; 
 
//Instantiater 
 
function createMemory() { 
 
    return new Memory({ 
 
    wrapperID: 'memory-game' 
 
    }); 
 
}; 
 

 
//Instantiate 
 
var m = new createMemory(); 
 
//Call inherited 
 
console.log(m); 
 
m.options.onGameEnd();
對象的

屬性是特定於對象的該實例,而原型的屬性是對象的實例之間共享。

例如,如果您有每個實例的ID號,那麼ID屬性需要位於Object上,因爲它對於該實例是唯一的。相反,如果你有一個與所有實例完全相同的方法,那麼你可以通過將它放入Prototype並簡單地繼承它來節省內存。

+0

感謝那 但是,我的問題不是爲什麼我的代碼工作/不工作,而是一個關於對象和原型的一般問題 –

+0

好,幫助我,比如,75% 什麼,我仍然不現在得到的是:當我創建一個新的存儲器M,它需要所有屬性從樣機,對不對?但不應該採用我在函數Memory中定義的所有屬性麼? m是用內存的「計劃」構建的,畢竟 –

+0

它確實使用了所有用「Memory」定義的元素。您始終可以覆蓋特定實例的原型屬性。 –

相關問題