简体   繁体   中英

ES6 Classes: Is this a proof for prototype extending another one?

While playing around with Babel.js and doing some extending with classes I realized something that might be a good way to differentiate common class inheritance (Java, C#...) and prototype (I don't really say class here somehow) inheritance.

Given the following to base-class:

class Menu {

  constructor(){}

  render(){
    this.addObjectsToStage();
  }

  addObjectsToStage() {
    var objects = this.objects.getAllObjects();
    for (var category in objects) {
      if (objects.hasOwnProperty(category)) {
        for (var type in objects[category]) {
          if (objects[category].hasOwnProperty(type))
            this.stage.addChild(objects[category][type]);
        }
      }
    }
  }

}

And its subclass:

class MainMenu extends Menu{

  constructor(stage, options) {
    super();
    this.stage = stage;
    this.objects = new MenuObjects(options);
  }
}

Now what I want to point out is that the super-class Menu is calling a property this. objects .getAllObjects() ( in function "addObjectsToStage" ).

In a "common" object orientated language you wouldn't be able to access a property which is just defined when an instance of a sub-class is being created. So this, in my opinion, is a significant sign for a difference in inheritance styles.

So what I'd like to know now is if I'm pretty right or dead wrong!

Im not good in the class inheritance in language like java or c#. But your example will work in javascript. But as said in the comment, it will only work if the Menu instance is a MainMenu instance.

I see many java devs comming in javascript and dont understand the freedom of javascrpit. They need and want tools that tell them if what they write work or not. That's why we see more and more sub-language build on top of javascript to have a "class inheritance" feeling. But that's not the way javascript work. So they better learn and read about closure, function scope and also prototyping. Javascrpit is really simple and it force you to write good and logic code.

So the answer for me is : yes your pretty right. This is a significsnt sign of the difference between class and prototypal inheritance.

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