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",
};
class Mod extends shapez.Mod {
init() {
this.modInterface.extendClass(shapez.MetaBeltBuilding, {
// this replaces a regular method
const BeltExtension = ({ $super, $old }) => ({
getShowWiresLayerPreview() {
return true;
// Access the old method
return !$old.getShowWiresLayerPreview();
},
// Instead of super, use this.$super()
getIsReplaceable() {
return this.$super.getIsReplaceable.call(this);
// Instead of super, use $super
return $super.getIsReplaceable.call(this);
},
getIsRemoveable() {
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));
base.$super = base.$super || {};
/**
*
* @param {typeof Object} classHandle
* @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 => {
if (["constructor", "name", "length", "prototype"].includes(propertyName)) {
if (["constructor", "prototype"].includes(propertyName)) {
return;
}
base.$super[propertyName] = base.$super[propertyName] || base[propertyName];
base[propertyName] = extension[propertyName];
$old[propertyName] = prototype[propertyName];
prototype[propertyName] = extensionMethods[propertyName];
});
};
extendPrototype(classHandle.prototype, extensionClass);
}
}