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

Add helper methods to extend classes

This commit is contained in:
tobspr 2022-01-16 20:30:51 +01:00
parent 7e0689694c
commit e942ba486e
2 changed files with 47 additions and 0 deletions

View File

@ -0,0 +1,32 @@
/**
* Shows how to extend builtin classes
*/
const METADATA = {
website: "https://tobspr.io",
author: "tobspr",
name: "Mod Example: Class Extensions",
version: "1",
id: "class-extensions",
description: "Shows how to extend builtin classes",
};
class Mod extends shapez.Mod {
init() {
this.modInterface.extendClass(shapez.MetaBeltBuilding, {
// this replaces a regular method
getShowWiresLayerPreview() {
return true;
},
// Instead of super, use this.$super()
getIsReplaceable() {
return this.$super.getIsReplaceable.call(this);
},
getIsRemoveable() {
return false;
},
});
}
}

View File

@ -388,4 +388,19 @@ export class ModInterface {
return returnValue;
};
}
extendClass(classHandle, extensionClass) {
const extendPrototype = function (base, extension) {
const properties = Array.from(Object.getOwnPropertyNames(extension));
base.$super = base.$super || {};
properties.forEach(propertyName => {
if (["constructor", "name", "length", "prototype"].includes(propertyName)) {
return;
}
base.$super[propertyName] = base.$super[propertyName] || base[propertyName];
base[propertyName] = extension[propertyName];
});
};
extendPrototype(classHandle.prototype, extensionClass);
}
}