Skip to content

Handy Manual

Aryan Chudasama edited this page Apr 6, 2020 · 3 revisions

extend-bases: Handy manual

Installation

Simply run:

npm add extend-bases

Or:

yarn add extend-bases

To import:

import {bases, defineProperties, isInstanceOf} from "extend-bases";

Or:

const {bases, defineProperties, isInstanceOf} = require("extend-bases");

The bases method

class Activatable {
	val: boolean;

	constructor (val: boolean) {
		this.val = val;
	}

	activate () {
		this.val = true;
	}

	deactivate () {
		this.val = false;
	}

	get (): boolean {
		return this.val;
	}
}

class Accumulator {
	val: number;

	constructor (result: number) {
		this.val = result;
	}

	add (val: number) {
		this.val += val;
	}

	get (): number {
		return this.val;
	}
}

// Now let’s declare a new class inheriting from both of the classes:
class NewClass extends bases(Activatable, Accumulator) {
	constructor () {
		// To initialize the bases create a new instance of them and pass them to the constructor of the super class, now you will no longer need the `super` keyword.
		super(
			new Activatable(true),
			new Accumulator(0),
		);
	}

	getBoth () {
		// To get a specific base use `this.base[index]` where index is the index of the base as given in the bases function.
		return `Gotten: ${this.bases[0].get()} ${this.bases[1].get()}`
	}
}

const n = new NewClass();
console.log(n.val); // true: The base given first is given preference.
console.log(n.get()); // true: The base given first is given preference, of course.
n.add(10);
n.deactivate();
console.log(n.val, n.bases[1].val); // false 10: The bases are isolated, one can't affect the other, not directly that is.

The defineProperties method

There is a caveat in setting properties, if you directly set a property in the constructor and the super class has the same property name then it will be overwritten, and the super class will refer to the same property, and things may break.

This is not due to this library, this is due to the inherent dynamic nature of JavaScript.

But, this library isolates the derived and base classes, ie prevents collision of their properties and methods.

Thus, this problem can be avoided by using the defineProperties method from this library, if you use the bases methods as well.

In the constructor, just write (after importing it of course):

defineProperties(this, {
    <prop>: <value>, // Define a property on `this` with the name <prop> and value <value>
    "readonly <>": <value>, // Define a readonly property on `this` with the name <prop> and value <value>, readonly ie any attempts to edit it in strict mode will fail with a TypeError.
});

The isInstanceOf method

Obviously, the instanceof operator won’t work in this case, so we have to use the isInstanceOf method, it’s as simple as:

isInstanceOf(<obj>, <class>)

where <obj> is the object and <class> is the class.

And, that’s it, this library is just that simple.