ES 6 dynamically work on class after definition - javascript

I was previously rolling my own Javascript OOP but now I'm playing with ES6 and want to use the class defined after definition in a generic way.
Note
Any answer with new in it is not what I'm after.
Pseudo code:
// base.js
class Base {
constructor(arg) {
this.arg = arg;
}
// This is the behaviour I'm after
//afterDefined(cls) {
afterExtended(cls) { // probably a better name
console.log(`Class name ${cls.prototype.name}`);
}
}
// frombase.js
class FromBase extends Base {
constructor({ p1='val1', p2='val2'} = {}) {
super(...arguments);
this.p1 = p1;
this.p2 = p2;
}
}
The output in the console should be:
'Class name FromBase'
So far the only solution I have come up with is to have a static method on Base and call it after the class declaration when I define a new class but I will most likely forget to do this more than once.
Just to be really thorough on why I don't like the static solution; it will force me to import Base in every single file.
Example using a static method (which I don't want) https://jsfiddle.net/nL4atqvm/:
// base.js
class Base {
constructor(arg) {
super(...arguments);
this.arg = arg;
}
// This is the behaviour I'm after
static afterExtended(cls) {
console.log(`Class name ${cls.name}`);
}
}
// frombase.js
class FromBase extends Base {
}
// just after defining the FromBase class
Base.afterExtended(FromBase);

There is no javascript built-in trigger that is calling a method on a class when a subclass is defined that extends from it.
Because you're rolling your own library, you could craft some kind of method the creates and returns a new class that extends a given base class. Maybe check out this answer that may help how to define your classes: Instantiate a JavaScript Object Using a String to Define the Class Name
You could also check how other javascript libraries creates (sub)classes. For example, Ext JS has a ClassManager that you could look into.
http://docs.sencha.com/extjs/6.5.1/classic/Ext.ClassManager.html (docs)
http://docs.sencha.com/extjs/6.5.1/classic/src/ClassManager.js.html (source)
When this question would be about instantiation and not about defining classes, I would say:
afterDefined(cls) {
console.log(`Class name ${this.constructor.name}`);
}
Usage:
let x = new FromBase()
x.afterDefined() // --> Class name FromBase
To get the name of the class, use
static afterDefined(cls) {
console.log(`Class name ${this.name}`);
}

Is this what you're looking for?
class Base {
constructor(arg) { this.arg = arg; }
static afterDefined(cls) {
console.log(`Class name ${this.constructor.name}`);
}
}
Base = new Proxy(Base, {
get: function(target, key, receiver) {
if (typeof target == 'function' && key == 'prototype' && target.name == Base.name) {
Reflect.apply(Base.afterDefined, Reflect.construct(class FromBase {}, []), [])
}
return target[key];
}
});
class FromBase extends Base {}
In order for this to load class names, you will have to embed or forward-declare that information inside of the Proxy receiver prior to extending from it (which means you either need to enumerate ahead of time which classes you'll be inheriting to or to have some function call just prior to that class's declaration).
There are a bunch of other neat total hacks in the same vein such as looking at the source (text) of the file that you just loaded JavaScript from and then parsing that text as if it were JavaScript (people have used this to write Scheme interpreters that can accept new code inside of <script> tags).
If you are a library author intending to target Node, there are even more ways to go about doing this.

// base.js
class Base {
constructor(arg) {
this.arg = arg;
}
// This is the behaviour I'm after
afterDefined(cls) {
console.log(`Class name ${cls}`);
}
}
// frombase.js
class FromBase extends Base {
constructor(arg) {
super(arg)
}
}
let f = new FromBase();
f.afterDefined('text');//this you text or object
have to be aware of is. file loading order, super is an instance of the parent class. good luck.

Related

Is it possible for a javascript class to define a method which fires if the class is called?

In python there's something like __call__ for this. Consider the following example:
class MyClass {
__call__() { return 'called!' }
}
const myType = new MyClass();
myType(); // called!
The question is what should I replace __call__ with?
I was doing some research, and most of the answers recommend __proto__, but it doesn't seem to work.
It is not possible out-of-the-box, but you can extend Function, and use the Function constructor to forward a call to __call__. If you have multiple classes that need this feature, extend Function only once into -- let's say -- a Callable class, and then inherit your other classes from that:
class Callable extends Function {
constructor() {
super("...args", "return this.__call__(...args)");
return this.bind(this);
}
}
class Class extends Callable {
__call__() { return 'called!' }
}
let inst = new Class();
console.log(inst());
Background
In JavaScript an object is callable when, and only if, it has the [[Call]] internal slot. But there is (currently) no way to give any given object this slot via JavaScript code. One must start with a function object and extend that.
Adding a constructor, inheritance
The above solution allows the constructor to define properties in the usual way: the constructed object is an instance of the class:
class Callable extends Function {
constructor() {
super("...args", "return this.__call__(...args)");
return this.bind(this);
}
}
class Class extends Callable {
constructor(data) {
super();
this.x = data;
}
__call__() { return 'called!' }
}
let inst = new Class(42);
console.log(inst instanceof Class); // true
console.log(inst.x); // 42
console.log(inst());
You can use constructor.
class Example {
constructor() {
// gets called on class initialization
}
}
Inside the constructor you can also call other methods if you want.
However this won't create an invoke function like using PHP's __invoke if that's what you meant. If that's what you're looking for then I don't know.

Implementing JS decorator to wrap class

I'm trying to wrap class constructor and inject to some logic by using class decorator. Everything worked fine until I have tried to extend wrapped class: Extended class don't have methods in prototype.
function logClass(Class) {
// save a reference to the original constructor
const _class = Class;
// proxy constructor
const proxy = function(...args) {
const obj = new _class(...args);
// ... add logic here
return obj
}
// copy prototype so intanceof operator still works
proxy.prototype = _class.prototype;
// return proxy constructor (will override original)
return proxy;
}
#logClass
class Base {
prop = 5;
test() {
console.log("test")
}
}
class Extended extends Base {
test2() {
console.log("test2")
}
}
var base = new Base()
base.test()
var ext = new Extended()
console.log(ext.prop)
ext.test()
ext.test2() // TypeError: ext.test2 is not a function
Okay so I tried to figure out what is "wrong" with your code, but I was not able to make it work because it didn't typecheck. So, as a last resort, I'm posting a partial answer of my attempt, which works (with some quirks) so I can help other users who are more savvy with TypeScript.
First of all, the quirks: class decorators in TS cannot modify the structure of a type, so if you wanted to, for example, add a method to the decorated class, you would be able to do it but you would have to eat up/suppress unavoidable type errors (TS2339) when calling those methods.
There is a work around for this in this other question: Typescript adding methods with decorator type does not exist, but you would lose this current clean syntax for decorators if you do this.
Now, my solution, taken more or less directly from the documentation:
function logClass<T extends { new(...args: any[]): {} }>(constructor: T) {
return class extends constructor {
constructor(...args: any[]) {
super(args);
// ...add programmatic logic here
// (`super` is the decorated class, of type `T`, here)
}
// ...add properties and methods here
log(message: string) { // EXAMPLE
console.log(`${super.constructor.name} says: ${message}`);
}
}
}
#logClass
class Base {
prop = 5;
test() {
console.log("test");
}
constructor() {}
}
class Extended extends Base {
test2() {
console.log("test2");
}
}
var base = new Base();
base.test();
var ext = new Extended();
console.log(ext.prop);
//base.log("Hello"); // unavoidable type error TS2339
ext.test();
ext.test2();

How to call inherited symbol that computed!? as Function in extended class?

First of all I'm a newbie in Typescript so title may be inaccurate because I don't know how that code works properly.
I'm using the Klasa framework which is a Discord bot framework made top of Discord.js. They recently added plugin functionality and there is lots of examples written in regular ES6...
const { Client, util: { mergeDefault } } = require('klasa');
const DriverStore = require('../lib/structures/DriverStore');
const { OPTIONS } = require('../lib/util/constants');
class MusicClient extends Client {
constructor(config) {
super(config);
this.constructor[Client.plugin].call(this);
}
static [Client.plugin]() {
mergeDefault(OPTIONS, this.options);
this.drivers = new DriverStore(this);
this.registerStore(this.drivers);
}
}
module.exports = MusicClient;
Type of Client.plugin is Symbol. How this code work? And how can I achieve something similar to this with TypeScript or it is doable?
I tried doing it like this:
import { KlasaClientOptions, Client } from "klasa"
export class ExtendedClient extends Client {
public prop: string;
constructor(options: KlasaClientOptions) {
super(options);
// Element implicitly has an 'any' type 'typeof KlasaClient' has no index signature.
this.constructor[Client.plugin].call(this);
// Also trying to use ExtendedClient.plugin.call() gives me
// Property 'call' does not exist on type 'symbol'
}
static [Client.plugin]() {
// Property 'prop' does not exist of type 'typeof ExtendedClient'
this.prop = "somestring";
}
}
Edit: I fixed the error after I found out static [Client.plugin]() has the context of KlasaClient so I changed it as
import { KlasaClientOptions, Client } from "klasa"
export class ExtendedClient extends Client {
public prop: string;
constructor(options: KlasaClientOptions) {
super(options);
(this.constructor as any)[Client.plugin].call(this);
}
static [Client.plugin](this: ExtendedClient) {
this.prop = "somestring";
}
}
and the problems are solved...
The code is fairly odd, and unless there's a strong design constraint forcing it to be that way, it's not best practice.
It's defining a static method, but calling it as though it were an instance method. Which is part of why TypeScript is having issues with it.
The key parts are:
This:
static [Client.plugin]() {
this.registerStore(this.drivers);
}
...which defines a static method (a method on the constructor function) with the name from Client.plugin (which you've said is a Symbol, but it doesn't really matter whether it's a Symbol or a string).
And this in the constructor:
this.constructor[Client.plugin].call(this);
...which is what's calling it as though it were an instance method. this.constructor accesses the constructor function that created this (loosely speaking, that's not entirely accurate), and so this.constructor[Client.plugin] accesses the static method with the name from Client.plugin. Then .call(this) calls that method, but sets this as this during the call, a though it were an instance method. So within the call to Client.plugin, this is an instance of the class (whereas normally this would be the constructor function).
Which is very odd.
In terms of making TypeScript okay with it, I think I'd probably approach it like this:
import { KlasaClientOptions, Client } from "klasa";
export class ExtendedClient extends Client {
public prop: string;
constructor(options: KlasaClientOptions) {
super(options);
(this.constructor as any)[Client.plugin].call(this);
}
static [Client.plugin]() {
const inst = this as ExtendedClient;
// Now use `inst` instead of `this` where your example code uses `this`, so:
inst.prop = "somestring";
}
}
The key bits are:
This:
(this.constructor as any)[Client.plugin].call(this);
...by using any we defeat TypeScript's type checking, but we basically have to for this odd structure.
And this:
const inst = this as ExtendedClient;
...by using as ExtendedClient we're telling TypeScript that although normally it would expect this to be the constructor function, it's actually an ExtendedClient. We do that once with a constant to avoid having to repeat it everywhere.

Javascript ES6: How to retrieve calling subclass from a static method defined in superclass

New to JavaScript.
Seeking some guidance on how to access the calling class name from a static method defined in the superclass using ES6 classes. I've spent an hour searching, but have not been able to come up with a solution.
A code snippet may help clarify what I am seeking
class SuperClass {
get callingInstanceType() { return this.constructor.name }
static get callingClassType() { return '....help here ...' }
}
class SubClass extends SuperClass { }
let sc = new SubClass()
console.log(sc.callingInstanceType) // correctly prints 'SubClass'
console.log(SubClass.callingClassType) // hoping to print 'SubClass'
As illustrated above, I can easily get the subclass name from a instance. Not quite sure how to access from a static method.
Ideas for the implementation of static get callingClassType() welcomed.
callingClassType is a function (well, a getter in this case, same thing). The value of this inside a function depends on how it is called. If you call a function with foo.bar(), then this inside bar will refer to foo.
Thus if you "call" the function with SubClass.callingClassType, this will refer to SubClass. SubClass is itself a (constructor) function thus you can get its name via the name property.
So your method definition should be
static get callingClassType() { return this.name; }
class SuperClass {
get callingInstanceType() {
return this.constructor.name
}
static get callingClassType() {
return this.name
}
}
class SubClass extends SuperClass {}
let sc = new SubClass()
console.log(sc.callingInstanceType)
console.log(SubClass.callingClassType)
Have a look at the MDN documentation to learn more about this.
Use SuperClass.prototype.constructor.name:
class SuperClass {
get callingInstanceType() { return this.constructor.name }
static get callingClassType() { return SuperClass.prototype.constructor.name; }
}
class SubClass extends SuperClass {}
class SubClass2 extends SuperClass {
static get callingClassType() { return SubClass2.prototype.constructor.name; }
}
console.log(SuperClass.callingClassType); // 'SuperClass'
console.log(SubClass.callingClassType); // 'SuperClass'
console.log(SubClass2.callingClassType); // 'SubClass2'
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static#Examples:
class Triple {
static triple(n) {
if (n === undefined) {
n = 1;
}
return n * 3;
}
}
class BiggerTriple extends Triple {
static triple(n) {
return super.triple(n) * super.triple(n);
}
}
console.log(Triple.triple()); // 3
console.log(Triple.triple(6)); // 18
var tp = new Triple();
console.log(BiggerTriple.triple(3));
// 81 (not affected by parent's instantiation)
console.log(tp.triple());
// 'tp.triple is not a function'.

Why are derived class property values not seen in the base class constructor?

I wrote some code:
class Base {
// Default value
myColor = 'blue';
constructor() {
console.log(this.myColor);
}
}
class Derived extends Base {
myColor = 'red';
}
// Prints "blue", expected "red"
const x = new Derived();
I was expecting my derived class field initializer to run before the base class constructor.
Instead, the derived class doesn't change the myColor property until after the base class constructor runs, so I observe the wrong values in the constructor.
Is this a bug? What's wrong? Why does this happen? What should I do instead?
Not a Bug
First up, this is not a bug in TypeScript, Babel, or your JS runtime.
Why It Has To Be This Way
The first follow-up you might have is "Why not do this correctly!?!?". Let's examine the specific case of TypeScript emit. The actual answer depends on what version of ECMAScript we're emitting class code for.
Downlevel emit: ES3/ES5
Let's examine the code emitted by TypeScript for ES3 or ES5. I've simplified + annotated this a bit for readability:
var Base = (function () {
function Base() {
// BASE CLASS PROPERTY INITIALIZERS
this.myColor = 'blue';
console.log(this.myColor);
}
return Base;
}());
var Derived = (function (_super) {
__extends(Derived, _super);
function Derived() {
// RUN THE BASE CLASS CTOR
_super();
// DERIVED CLASS PROPERTY INITIALIZERS
this.myColor = 'red';
// Code in the derived class ctor body would appear here
}
return Derived;
}(Base));
The base class emit is uncontroversially correct - the fields are initialized, then the constructor body runs. You certainly wouldn't want the opposite - initializing the fields before running the constructor body would mean you couldn't see the field values until after the constructor, which is not what anyone wants.
Is the derived class emit correct?
No, you should swap the order
Many people would argue that the derived class emit should look like this:
// DERIVED CLASS PROPERTY INITIALIZERS
this.myColor = 'red';
// RUN THE BASE CLASS CTOR
_super();
This is super wrong for any number of reasons:
It has no corresponding behavior in ES6 (see next section)
The value 'red' for myColor will be immediately overwritten by the base class value 'blue'
The derived class field initializer might invoke base class methods which depend on base class initializations.
On that last point, consider this code:
class Base {
thing = 'ok';
getThing() { return this.thing; }
}
class Derived extends Base {
something = this.getThing();
}
If the derived class initializers ran before the base class initializers, Derived#something would always be undefined, when clearly it should be 'ok'.
No, you should use a time machine
Many other people would argue that a nebulous something else should be done so that Base knows that Derived has a field initializer.
You can write example solutions that depend on knowing the entire universe of code to be run. But TypeScript / Babel / etc cannot guarantee that this exists. For example, Base can be in a separate file where we can't see its implementation.
Downlevel emit: ES6
If you didn't already know this, it's time to learn: classes are not a TypeScript feature. They're part of ES6 and have defined semantics. But ES6 classes don't support field initializers, so they get transformed to ES6-compatible code. It looks like this:
class Base {
constructor() {
// Default value
this.myColor = 'blue';
console.log(this.myColor);
}
}
class Derived extends Base {
constructor() {
super(...arguments);
this.myColor = 'red';
}
}
Instead of
super(...arguments);
this.myColor = 'red';
Should we have this?
this.myColor = 'red';
super(...arguments);
No, because it doesn't work. It's illegal to refer to this before invoking super in a derived class. It simply cannot work this way.
ES7+: Public Fields
The TC39 committee that controls JavaScript is investigating adding field initializers to a future version of the language.
You can read about it on GitHub or read the specific issue about initialization order.
OOP refresher: Virtual Behavior from Constructors
All OOP languages have a general guideline, some enforced explicitly, some implicitly by convention:
Do not call virtual methods from the constructor
Examples:
C# Virtual member call in a constructor
C++ Calling virtual functions inside constructors
Python Calling member functions from a constructor
Java Is it OK to call abstract method from constructor in Java?
In JavaScript, we have to expand this rule a little
Do not observe virtual behavior from the constructor
and
Class property initialization counts as virtual
Solutions
The standard solution is to transform the field initialization to a constructor parameter:
class Base {
myColor: string;
constructor(color: string = "blue") {
this.myColor = color;
console.log(this.myColor);
}
}
class Derived extends Base {
constructor() {
super("red");
}
}
// Prints "red" as expected
const x = new Derived();
You can also use an init pattern, though you need to be cautious to not observe virtual behavior from it and to not do things in the derived init method that require a complete initialization of the base class:
class Base {
myColor: string;
constructor() {
this.init();
console.log(this.myColor);
}
init() {
this.myColor = "blue";
}
}
class Derived extends Base {
init() {
super.init();
this.myColor = "red";
}
}
// Prints "red" as expected
const x = new Derived();
I would respectfully argue this is, in fact, a bug
By doing an unexpected thing, this is undesired behavior that breaks common class extension use cases. Here is the initialization order that would support your use case and that I would argue is better:
Base property initializers
Derived property initializers
Base constructor
Derived constructor
Problems / Solutions
- The typescript compiler currently emits property initializations in the constructor
The solution here is to separate the property initializations from the calling of the constructor functions. C# does this, although it inits base properties after derived properties, which is also counterintuitive. This could be accomplished by emitting helper classes so that the derived class can initialize the base class in an arbitrary order.
class _Base {
ctor() {
console.log('base ctor color: ', this.myColor);
}
initProps() {
this.myColor = 'blue';
}
}
class _Derived extends _Base {
constructor() {
super();
}
ctor() {
super.ctor();
console.log('derived ctor color: ', this.myColor);
}
initProps() {
super.initProps();
this.myColor = 'red';
}
}
class Base {
constructor() {
const _class = new _Base();
_class.initProps();
_class.ctor();
return _class;
}
}
class Derived {
constructor() {
const _class = new _Derived();
_class.initProps();
_class.ctor();
return _class;
}
}
// Prints:
// "base ctor color: red"
// "derived ctor color: red"
const d = new Derived();
- Won't the base constructor break because we're using derived class properties?
Any logic that breaks in the base constructor can be moved to a method that would be overridden in the derived class. Since derived methods are initialized before the base constructor is called, this would work correctly. Example:
class Base {
protected numThings = 5;
constructor() {
console.log('math result: ', this.doMath())
}
protected doMath() {
return 10/this.numThings;
}
}
class Derived extends Base {
// Overrides. Would cause divide by 0 in base if we weren't overriding doMath
protected numThings = 0;
protected doMath() {
return 100 + this.numThings;
}
}
// Should print "math result: 100"
const x = new Derived();

Categories