2016-02-28 46 views
0

我真的很努力地找到非常簡單和實用的例子(例如在MDN),但它讓我發瘋。我不能簡單地弄清楚,我犯了錯誤。我想有一個Array對象的祖先。這裏是示例。如何在javascript中製作對象的子對象?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Fiddling</title> 
<script> 


function Synthese() { 
    //Array.call(this); 
    //Synthese.prototype = Object.create(Array.prototype); 
    //Synthese.prototype.constructor = Synthese; 

    this.prototype = Object.create(Array); 
    //this.prototype.constructor = this; 
    this.Make = function() { 
     result = ""; 
     for (i=0; i<this.length; i++){ 
     result = result + this[i] + ".";  
     } 
     return result; 
    } 
} 
var A = new Array(); 
A.push("A"); //OK 
var S = new Synthese(); 
S.push("A"); //fails 
S.push("B"); 
alert(S.Make()); 
</script> 
</head> 
<body> 
</body> 
</html> 

如何使Synthese成爲Array的子​​項? S.push( 「A」);從不執行

+0

的[如何在JavaScript中的類繼承?]可能的複製(http://stackoverflow.com/questions/2107556/how-to-inherit-from設置原型-a-class-in-javascript) – AMACB

+0

是否有錯誤? –

+0

@ zer00ne:它可以是任何東西,這裏的字符串... – lyborko

回答

0

你應該構造後

.. 
    function Synthese() { 
     //Array.call(this); 
     //Synthese.prototype = Object.create(Array.prototype); 
     //Synthese.prototype.constructor = Synthese; 

     this.prototype = Object.create(Array); 
     //this.prototype.constructor = this; 
     this.Make = function() { 
      result = ""; 
      for (i=0; i<this.length; i++){ 
      result = result + this[i] + ".";  
      } 
      return result; 
     } 
    } 
    Synthese.prototype = []; // HERE 
    var A = new Array(); 
    A.push("A"); 
    console.log(Object.getPrototypeOf(S)); 
    S.push("A"); 
    S.push("B"); 
    alert(S.Make()); 
.. 
+0

不,它不起作用。我嘗試了幾種組合......沒有成功...... – lyborko

+0

我做了一個小提琴,只是運行它https://jsfiddle.net/nikishkinvv/4v3r4acs/。這產生結果「A.B.」。這是不對的? –

+0

這是正確的....令人難以置信的...... :-)。爲什麼我必須在對象構造器之外聲明原型仍然是我的謎...奇怪。我必須考慮它......無論如何,你的答案是正確的,所以有人可以回答,爲什麼它被拒絕投票。非常感謝。 – lyborko

3

您無法在ES5或更低版本中正確繼承Array。這是繼承機制的幾個限制之一。

,這是固定在ES2015(又名ES6),通過新的class關鍵字:

// ES2015 and above only 
class Synthese extends Array { 
} 

此功能不能勻/由像巴貝爾transpilers(因爲你不能做到這一點在ES5,你polyfilled需要JavaScript引擎在ES2015之前不具備的功能)。


無關Array問題,你的執行派生構造函數的模式是不完全正確。如果您仍然需要在ES5中執行此操作並且沒有使用轉譯器,我已經寫了一個詳盡的解釋和示例in this answer

+0

這是什麼意思,你不能正確地繼承數組? – lyborko

+0

@lyborko:這意味着:你無法從'Array'正確繼承(在ES5和更早版本中)。這是不能做到的。 'Array'對象有一些非常特殊的行爲(主要是'length'屬性),如果你試圖在ES5和更早的版本中創建一些從'Array'繼承的東西,那麼它們就不能正常工作。它需要對語言規範和JavaScript引擎進行更改才能在ES2015中實現。 –

+0

謝謝你的解釋。所以我會盡力解決。希望在對象構造函數中實例化數組可能是正確的。像:this.Arr = new Array();然後在代碼Synthese.Arr.push(「A」); – lyborko

相關問題