python - Using components in Javascript -
i'm relatively new javascript. wondering if supports components , objects python does. if does, syntax like?
for instance, know object this:
function foo(a, b) { this.a = a; this.b = b; } now, there way declare components, pick 1 of those, , add object? instance, let's have object item. declare different components, such weapon, magical, legendary, etc. , them add them object? using approach end magical weapon, or legendary item, or legendary magical weapon.
i thought using parenting want do, seems rather limited. instance, heirarchy item/weapon or item/legendary, couldn't have legendary weapon.
so, components possible in javascript?
what describe 'component' more commonly called class. describe 'parenting' more commonly called inheritance. spot on class hierarchy :)
ok, base class in item. item have basic attributes items in game world must have. objects in game world inherit item.
a weapon item. magicalitem item. legendaryitem item. these 3 classes subclasses of item.
things little bit more tricky when want legendarymagicalweaponitem. essence of question: multiple inheritance possible in javascript?
to paraphrase boondock saints, not want multiple inheritance unless absolutely, positively sure need it. why? leads complications. example, if 2 superclasses have method or attribute same name? if inherit 2 different base classes, , 1 of those classes causes name collision? can see going.
fortunately, javascript, python, flexible language. not forced use multiple inheritance or interfaces generalise behaviour across heterogeneous objects.
let's magicalitem has mana property , legendaryitem has legacy() method. let's weapon object has damage. let's item has important physical attributes , bunch of physics methods; 'dominant' superclass. there nothing stopping doing this:
// base classes function item() { // default values... } item.prototype.physics = function (t) {/* physics stuff */} function magical(mana) { this.mana = mana; } function weapon(damage) { this.damage = damage; } function legendary(legacy) { this.legacy = function () {return legacy;}; } // actual world item class function mylegendarymagicalsword(x,y) { this.x = x; this.y = y; weapon.call(this, mylegendarymagicalsword.damage); legendary.call(this, mylegendarymagicalsword.lore); magical.call(this, mylegendarymagicalsword.start_mana); } // actual prototypal inheritance mylegendarymagicalsword.prototype = new item(); // class attributes mylegendarymagicalsword.damage = 1000; mylegendarymagicalsword.start_mana = 10; mylegendarymagicalsword.lore = "an old sword."; // sword instance var sword = new mylegendarymagicalsword(0, 0); sword.physics(0); sword.mana; sword.legacy(); // etc // probe object supported interface if (sword.hasownproperty("damage")) { // it's weapon... } this down , dirty way describe.
> sword { x: 0, y: 0, damage: 1000, legacy: [function], mana: 10 }
Comments
Post a Comment