简体   繁体   中英

Real abstract method in javascript

I would like to create an abstract class in javascript, which implements certain methods, calls abstract ones and let the 'inherited' classes to implement these abstract ones. I've read a lot about js prototyping. Every single suggested implementation of abstract classes and methods in javascript seems to be a simple inheritance, but not real abstraction. Here is a really simple example to show what i want to achieve:

  var abstractClass = { abstractMethod: function() { /* i don't know yet what i'm going to do */ }, concreteMethod: function() { abstractClass.abstractMethod(); } } specializedClass = Object.create(abstractClass); specializedClass.abstractMethod = function() { alert('Now i know what to do'); } specializedClass.concreteMethod(); 

My question: is there a non-hacky, non-workaround way to make abstract classes in javascript?

inside the methods, use this instead of the named class/variable, which is duplicated/broken by your Object.create() call.

var abstractClass = {
  abstractMethod: function() { /* i don't know yet what i'm going to do */ },
  concreteMethod: function() {
    this.abstractMethod(); // < made generic with this 
  }
}


specializedClass = Object.create(abstractClass);
specializedClass.abstractMethod = function() {
  alert('Now i know what to do');
}

specializedClass.concreteMethod();

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