super()

devfish·2023년 1월 16일
0

Javascript

목록 보기
21/30

What is super?

We call super() inside of a subclass' constructor method in order to call the parent constructor... and that's pretty much what super is in JavaScript: a reference to the parent prototype

we use super to reference the parent prototype's constructor function

class Resource { constructor() { } }

class Widget extends Resource {
    constructor() {
        super();
        if (super.constructor === Resource.prototype.constructor) {
            console.log("It's true!");
        }
    }
}
  • must be specified before using this
  • if you have a constructor method in the sub-class, you need one in the parent class
    • JS only attaches an object instance to this once you get to the highest prototype in the chain: Object
    • Default return value from constructor method is this, and if there is no parent constructor, you will have no this value and it will stay undefined
  • JS will create a no-op version of a constructor for you if you don't explicitly create one in the lower level constructor (in subclass):
    constructor(...args) {
       super(...args);
    }

Auto-context switching!

JS will switch the current context for this for you, even if it's in the parent class!

class Parent {
    constructor() { }
    whoami() {
        console.log(this);  // will print out the current SUBCLASS object
    }
}

class Child extends Parent {
    constructor() { super(); }
    whoami() {
        console.log(this);  // will print out the current Child object
        super.whoami();
    }
}

let w = new Child();
w.whoami(); 

So you can do this instead:

class Bee {
    constructor() { }
    whoami() {
        console.log(this);  // will print out the current SUBCLASS object
    }
}

class WorkerBee extends Bee {
   // constructor() { super(); }
}

let w = new WorkerBee(); 
console.log(w.whoami()); 

How super determines its values

  • Function.prototype.call()
    calls the function with a given this value and arguments provided individually

References

Understanding Super in JS

How is the value of 'super' determined compared to 'this'?

profile
la, di, lah

0개의 댓글

관련 채용 정보