簡體   English   中英

多重繼承 ES6

[英]Multiple Inheritance ES6

我正在創建一個游戲,為此我創建了幾個可用於服務器端和客戶端的基類,例如部隊和步兵(擴展部隊)。 步兵類實現了諸如 isInfantry 之類的方法。

為了創建客戶端渲染,我創建了一個名為 TroopClient 的類,它擴展了 Troop 並向其屬性添加了一個精靈和一個移動這種精靈的方法。 之后我創建了擴展 TroopClient 的 InfantryClient。 現在這個 InfantryClient 有 sprites 屬性和方法,但是沒有實現 Infantry 方法。

我研究了混音,但我還沒有找到一篇關於 ES6 類的好文章,我不知道我的方法是否正確。

我正在尋找有關此問題的一些見解以及如何使用混入(如果這是一個好方法)來做到這一點(並附上一些解釋)。

ES6 或任何其他 ES/JS 版本不支持多重繼承或混合。 由於它是一種動態類型語言,您可以模仿行為,但這會有一些限制和缺點。 您可能需要在線查看一些示例以獲取解決方法。

這是我用來在 JS 中允許多重繼承的一種解決方法。 盡管您的里程可能會有所不同。

 var custom = function() { "use strict"; return { class: function(constructor,prototype) { constructor.prototype = prototype; return constructor; }, class_extends: function(bases,constructor,prototype) { for (var i = 0; i < bases.length; ++i) { var base = bases[i]; for (var property in base.prototype) { if (!prototype[property]) { prototype[property] = base.prototype[property]; } } } function bundledConstructor() { for (var i = 0; i < bases.length; ++i) { bases[i].apply(this,arguments); } constructor.apply(this,arguments); } constructor.prototype = prototype; bundledConstructor.prototype = prototype; return bundledConstructor; } }; }(); void function() { "use strict"; var Base_1 = custom.class( // Constructor function function() { }, // Prototype, shared between class instances // use for constant values & functions { overloadedFunction: function() { console.log("This is from base 1"); }, base_1_function: function() { console.log("This is from base 1"); } } ); var Base_2 = custom.class( function() { },{ base_2_function: function() { console.log("This is from base 2"); } } ); /* Derrived inherits properties, constants & functions from base_1 & base_2 if anything is redeclared in Derrived, it is considered overloaded (When a new Derrived object is made, the constructors for base_1 & base_2 are called first) */ var Derrived = custom.class_extends([Base_1,Base_2], function() { },{ overloadedFunction: function() { console.log("This is from derrived"); } } ); onload = function() { var derrived = new Derrived(); derrived.base_1_function(); derrived.base_2_function(); derrived.overloadedFunction(); } }();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM