How do I call a super constructor outside a constructor? - javascript

Now that JavaScript has classes I'm wondering how it is possible to invoke a super constructor outside of a class constructor.
My unsuccessful naive attempt (results in a SyntaxError):
class A
{
constructor() { this.a = 1; }
}
function initB()
{
super(); // How to invoke new A() on this here?
this.b = 2;
}
class B extends A
{
constructor() { initB.call(this); }
}
I'm aware that in some other language like Java a super constructor can only be invoked inside the constructor of a derived class, but ES6 classes are syntactic sugar for prototype-based inheritance, so I'd be surprised if this were not feasible using built-in language features. I just can't seem to figure out the proper syntax.
The best I've come with so far feels terribly like cheating:
class A
{
constructor() { this.a = 1; }
}
function initB()
{
let newThis = new A();
newThis.b = 2;
return newThis;
}
class B extends A
{
constructor() { return initB(); }
}

Every constructor of a class that extends something must contain a direct super(…) call.
Direct super(…) calls can only be placed in constructors. There's really no way around this.
You really should not place the initialisation logic of a class anywhere else than in its constructor. The straightforward and proper solution is not to use initB at all:
class A {
constructor() { this.a = 1; }
}
class B extends A {
constructor() {
super();
this.b = 2;
}
}
That said, there is a way to subvert the "super() call must be in the constructor" requirement. Putting it inside an arrow function counts as well! So you could do
class A {
constructor() { this.a = 1; }
}
function initB(_super) {
var b = _super();
b.b = 2;
}
class B extends A {
constructor() {
initB(() => super());
}
}
Promise me to not ever do that, please.
Another pattern is not to call super() at all, which works as long as you return an object from the constructor. With that, you can put the actual construction of the object anywhere else:
class A {
constructor() { this.a = 1; }
}
function makeB() {
var b = Reflect.construct(A, [], B); // call the A constructor with B for the prototype
b.b = 2;
return b;
}
class B extends A {
constructor() {
return makeB();
}
}
Which really isn't much better.

Related

Javascript class composition : access attribute of secondary class in attribute of main class

Let's take this exemple :
class A {
attrA = 3;
}
class B {
constructor() {
this.a = new A;
}
attrB = this.a.attrA;
methB() { console.log(this.a.attrA);}
}
const test = new B;
console.log(test.attrB);
test.methB();
I can access the class A attribute through method of class B, but I can't use it with attribute of class B, I have an "undefined" error.
The only way to do this is :
class A {
attrA = 3;
}
class B {
constructor() {
this.a = new A;
this.z = this.a.attrA
}
methB() { console.log(this.a.attrA);}
}
const test = new B;
console.log(test.z);
test.methB();
Why I need to put the attribute in the constructor and not the method?
Thanks!
You can think of class fields as being hoisted, meaning this:
class Example {
constructor() {/*...*/}
property = "value";
}
Is "actually" this:
class Example {
property = "value";
constructor() {/*...*/}
}
Or (similar to) this:
class Example {
constructor() {
this.property = "value";
/*...*/
}
}
Further, identifiers are resolved upon access. So by the time you execute test.methB(), test.a has been initialized, allowing the method to correctly resolve this.a.attrA. It works the same as this code:
let variable = null;
const logVariable = () => console.log(variable); // You may think this logs null, but ...
variable = "value";
logVariable(); // ... it actually logs `variable`'s value at the time of calling.
As you have observed, mixing property initializations from within the constructor and using field initializers may be confusing. Therefore, a more intuitive way to write your code would be:
class A {
attrA = 3;
}
class B {
a = new A;
attrB = this.a.attrA;
constructor() {}
methB() {
console.log(this.a.attrA);
}
}
const test = new B;
console.log(test.attrB); // Works now!
test.methB();
Personal recommendations:
Declare all instance and class fields.
Prefer field initializers.
Only reassign/initialize fields in the constructor for non-default values.
You may want to read on for more details for a better technical understanding.
Class syntax
Classes are just uncallable constructor functions:
class Example {}
console.log(typeof Example); // "function"
Example(); // Error: cannot be invoked without `new`
This is a quirk of the ES6 class syntax. Technically, class constructors are still "callable", but only internally (which happens when using new). Otherwise constructors would serve no purpose.
Another aspect of the class syntax is the ability to call super() in the constructor. This only comes into play when a class inherits, but that comes with yet its own quirks:
You cannot use this before calling super:
class A {};
class B extends A {
constructor() {
this; // Error: must call super before accessing this
super();
}
}
new B();
Reason being, before calling super no object has been created, despite having used new and being in the constructor.
The actual object creation happens at the base class, which is in the most nested call to super. Only after calling super has an object been created, allowing the use of this in the respective constructor.
Class fields
With the addition of instance fields in ES13, constructors became even more complicated: Initialization of those fields happens immediately after the object creation or the call to super, meaning before the statements that follow.
class A /*no heritage*/ {
property = "a";
constructor() {
// Initializing instance fields
// ... (your code)
}
}
class B extends A {
property = "b";
constructor() {
super();
// Initializing instance fields
// ... (your code)
}
}
Further, those property "assignments" are actually no assignments but definitions:
class Setter {
set property(value) {
console.log("Value:", value);
}
}
class A extends Setter {
property = "from A";
}
class B extends Setter {
constructor() {
super();
// Works effectively like class A:
Object.defineProperty(this, "property", { value: "from B" });
}
}
class C extends Setter {
constructor() {
super();
this.property = "from C";
}
}
new A(); // No output, expected: "Value: from A"
new B(); // No output, expected: "Value: from B"
new C(); // Output: "Value: from C"
Variables
Identifiers are only resolved upon access, allowing this unintuitive code:
const logNumber = () => console.log(number); // References `number` before its declaration, but ...
const number = 0;
logNumber(); // ... it is resolved here, making it valid.
Also, identifiers are looked up from the nearest to the farthest lexical environment. This allows variable shadowing:
const variable = "initial-value";
{
const variable = "other-value"; // Does NOT reassign, but *shadows* outer `variable`.
console.log(variable);
}
console.log(variable);

import a method from a class into another class JS

I'm still beginner in JS and I feel like I'm often dealing with some basic stuffs out here.. I want to retrieve/import a method from a class A into class B (using modules). Also, I don't know if my code is well built so I'm open for all suggestions and advices.
Here's class 1 (A)
export default class A {
constructor() {
this.zone = document.getElementById('#zone');
this.array = [];
this.init();
}
init() {
//code
}
methodToImport(id) {
let DOM = `<h1>HTML Content</h1>`
this.zone.insertAdjacentHTML('beforeend', DOM);
this.array.push(new B(this.zone.lastElementChild));
}
and here's class 2 (B)
import A from "./A.js";
class B {
constructor(element) {
this.init();
}
init() {
// here I want to retrieve the array duly wholy fillen with instances of class A
console.log(A.array);
}
}
I really wish you could help, thank you guys !
you can create an object of class A in class B and use it.
class A {
constructor() {
this.zone = document.getElementById('#zone');
this.array = [1,2,3,4];
}
}
class B {
constructor(element) {
this.a = new A;
}
}
b = new B
console.log(b.a.array);

Not able to use 'super' with function defined on protoype object in JavaScript class

I have class A which is parent of class B
class A {
constructor(a){
this.a=a;
}
par(){
console.log("para");
}
}
class B extends A {
constructor(a) {
super(a)
this.a = "child";
}
par() {
super.par();
console.log("child");
}
}
When I use this code, it works fine.
But when I explicitly define the par function on B using this code:
B.prototype.par = function() {
super.par();
}
I get the error
Uncaught SyntaxError: 'super' keyword unexpected here
Whether we create a function in class definition or in prototype object of function('class'), it should be the same thing.
What am I doing wrong here?
'super' is simply a syntactic sugar introduced in ES2015 along with class syntax.
It can only be used within functions of 'class' (constructor and methods) that extends another class.
class A {
constructor(){}
par(){ console.log('para') }
}
class B extends A {
constructor(){
super()
}
}
Is equivalent to:
function A(){}
A.prototype.par = function(){console.log('para')}
var B = (function(parent){
var _super = parent;
function B(){
_super.call(this); // calls parent's constructor
}
B.prototype = Object.create(_super.prototype); // Inherits parent's methods.
B.prototype.par = function(){ // override parent's par.
_super.prototype.par.call(this); // child still has access to parent's par method thanks to closure :)
console.log('child');
}
return B;
})(A);
var b = new B();
b.par()
You cannot do:
function(){
super // super is not defined...
}

Use all functions of another object in javascript

I couldn't find the solution to this issue. I am banging my head against a wall entire day.
Assume we have the following hierarchy of classes:
class A {
async name() { ... }
}
class B extends A {
async age() { ... }
}
class C extends A {
async group() { ... }
}
class D extends B {
constructor() {
super(...)
this.C = new C(...);
}
async group() { return await this.C.group(); }
}
Because JavaScript doesn't support multiple inheritance, I have an issue. I would like to combine prototypes of objects in a way that I can invoke function group() without the need for writing repetitive code like above. It is absolute must to be able to invoke group() directly on the object D outside of the class, even though it is the an instance of class C.
How can I combine their prototypes? I've tried things like
class A {
appendPrototype(obj) {
if (obj instanceof A)
for (let k in obj.__proto__) {
this.__proto__[k] = obj.__proto__[k];
}
}
}
.
.
. // Same two classes, B and C
class D extends B {
constructor(...) {
super(...);
const c = new C(...);
this.appendPrototype(c);
}
}
I can't invoke the function group() an instance of the class D. Why is that? How can I achieve it, without writing repetitive code like in the first example?
What you can do, it is to assign to the prototype of the class D, the method of the class C.
In this way all the instances of D will have the group method which is the same method defined within the class C, and you can do the same for all the other child classes.
class A {
async name() {
console.log('A - name');
}
}
class B extends A {
async age() {
console.log('B - age');
}
}
class C extends A {
async group() {
console.log('C - group');
}
}
class D extends B {
constructor() {
super();
}
}
D.prototype.group = C.prototype.group;
const d = new D();
d.group();
Anyway, in your case, I would go for composition (like you did with C within D) and then call the methods like:
d.c.group()
which allows you to avoid the appendPrototype logic.

ES6 use `super` out of class definition

I'm trying to add extra methods to class, and these extra methods should use the super methods.
If I add them in the model definition, it works.
class A {
doSomething() {
console.log('logSomething');
}
}
class B extends A {
doSomething() {
super.doSomething();
console.log('logSomethingElse');
}
}
If I try to add the extra method to B.prototype, I'll get SyntaxError: 'super' keyword unexpected here.
class A {
doSomething() {
console.log('logSomething');
}
}
class B extends A {
}
B.prototype.doSomething = function doSomething() {
super.doSomething();
console.log('logSomethingElse');
}
It is quite clear, why I get this error. This is a function and not a class method.
Let's try to define the method as a class method, and copy it to the original B class:
class A {
doSomething() {
console.log('logSomething');
}
}
class B extends A {}
class X {
doSomething() {
super.doSomething();
console.log('2 logSomethingElse');
}
}
B.prototype.doSomething = X.prototype.doSomething;
In this case I'll get TypeError: (intermediate value).doSomething is not a function.
Is there any way to define methods (that refer to super) outside from the original class definition, and add these methods later to the original class?
super refers to ancestor of a class where the method was defined, it isn't dynamic. As Babel output illustrates this, super is hard-coded to Object.getPrototypeOf(X.prototype), and thus orphan class like this one doesn't make sense because it doesn't have super:
class X {
doSomething() {
super.doSomething();
...
}
}
But super can be substituted with dynamic counterpart:
doSomething() {
const dynamicSuper = Object.getPrototypeOf(this.constructor.prototype);
// or
// const dynamicSuper = Object.getPrototypeOf(Object.getPrototypeOf(this));
dynamicSuper.doSomething();
...
}
class B extends A {}
B.prototype.doSomething = doSomething;
In this case it will refer to ancestor class of class instance where doSomething was assigned as prototype method.
While I think this could be assumed as anti-pattern, you shouldn't use super outside from a class.
You can achieve that using Object Literals.
Refer to Object.setPrototypeOf
const A = {
sayHello() {
console.log("I am A");
},
Factory() {
return Object.create(this);
}
}
const B = {
sayHello() {
super.sayHello();
}
}
Object.setPrototypeOf(B, A);
const c = B.Factory();
c.sayHello();
If you don't make class X inherit from class B or A, the only way to call the method is A.prototype.doSomething() or more generally A.prototype.doSomething.call(this_substitute, ...args).

Categories

Resources