1
0
mirror of https://github.com/tobspr/shapez.io.git synced 2025-12-13 18:21:51 +00:00

Update class extensions

This commit is contained in:
tobspr 2022-01-17 19:11:04 +01:00
parent 1b931808eb
commit 0dac336670
2 changed files with 36 additions and 28 deletions

View File

@ -8,22 +8,24 @@ const METADATA = {
description: "Shows how to extend builtin classes", description: "Shows how to extend builtin classes",
}; };
class Mod extends shapez.Mod { const BeltExtension = ({ $super, $old }) => ({
init() {
this.modInterface.extendClass(shapez.MetaBeltBuilding, {
// this replaces a regular method
getShowWiresLayerPreview() { getShowWiresLayerPreview() {
return true; // Access the old method
return !$old.getShowWiresLayerPreview();
}, },
// Instead of super, use this.$super()
getIsReplaceable() { getIsReplaceable() {
return this.$super.getIsReplaceable.call(this); // Instead of super, use $super
return $super.getIsReplaceable.call(this);
}, },
getIsRemoveable() { getIsRemoveable() {
return false; return false;
}, },
}); });
class Mod extends shapez.Mod {
init() {
this.modInterface.extendClass(shapez.MetaBeltBuilding, BeltExtension);
} }
} }

View File

@ -389,18 +389,24 @@ export class ModInterface {
}; };
} }
extendClass(classHandle, extensionClass) { /**
const extendPrototype = function (base, extension) { *
const properties = Array.from(Object.getOwnPropertyNames(extension)); * @param {typeof Object} classHandle
base.$super = base.$super || {}; * @param {({ $super, $old }) => any} extender
*/
extendClass(classHandle, extender) {
const prototype = classHandle.prototype;
const $super = Object.getPrototypeOf(prototype);
const $old = {};
const extensionMethods = extender({ $super, $old });
const properties = Array.from(Object.getOwnPropertyNames(extensionMethods));
properties.forEach(propertyName => { properties.forEach(propertyName => {
if (["constructor", "name", "length", "prototype"].includes(propertyName)) { if (["constructor", "prototype"].includes(propertyName)) {
return; return;
} }
base.$super[propertyName] = base.$super[propertyName] || base[propertyName]; $old[propertyName] = prototype[propertyName];
base[propertyName] = extension[propertyName]; prototype[propertyName] = extensionMethods[propertyName];
}); });
};
extendPrototype(classHandle.prototype, extensionClass);
} }
} }