简体   繁体   中英

How to access es6 superclass member from its subclass?

So I'm tooling around with es6 classes but I'm a little stumped. My subclass needs to "shadow"/override a superclass method, but also use a member of the superclass (an instantiated eventemitter). How am I supposed to do this properly? Superclass (yes Eventemitter3extensionclass is available, also I do need external objects to be able to use the getter):

const eventemitter = new WeakMap(); 
export default class Uicomponentsuperclass {
  constructor() {
    eventemitter.set(this, new Eventemitter3extensionclass());
    // constructor
  }

get eventemitter() {
    return eventemitter.get(this);
  }

  ondosomething() {
    eventemitter.get(this).emit("emittedevent");
  }
// Uicomponentsuperclass
}

Subclass (showing unsuccessful attempts to access super's eventemitter):

export default class Subclass extends Uicomponentsuperclass {
  constructor() {
    super();
    // constructor
  }

ondosomething() { // shadowed 
    // eventemitter.get(this).emit("emittedevent"); // 
    // eventemitter.get(super).emit("emittedevent"); //  
    // eventemitter.get(super()).emit("emittedevent"); //  
    // super.eventemitter.emit("emittedevent"); //  
  }

In ondosomething , you need to reference this and use the eventemitter getter defined in your parent:

ondosomething() {
    this.eventemitter.emit("emittedevent");
}

this.eventemitter works like a property access and you can just use it like reading a property (even though it actually has getter code behind it).

This will access the eventemitter getter that your base class defines which will get you the Eventemitter3extensionclass object you want which you can then call .emit() on.

Note: This also assumes ondosomething is being called correctly and has the proper value of this . If that is not the case, then that also needs to be corrected. If you show us the calling code, we could advise on that. If you are passing obj.ondosomething as a callback, you may have to use .bind() as in obj.ondosomething.bind(obj) to assure the method is called properly bound to its object.


FYI, I can't figure out why you're using a weakMap to store these. Is there any reason the event emitter isn't just stored in the instance data of the base class? It seems that you've already made sure that there is a one-to-one correspondence between Uicomponentsuperclass objects and a corresponding Eventemitter3extensionclass object.

To invoke the Super class method from sub class, user super.methodName()

@Bergi was right again. OMG people, I have to own up. The error was being thrown by a different subclass... I'm blaming this on my allergies;-). Actually this works:

super.eventemitter.emit("emittedevent")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM