Question

Lets take the following example of inheritance in javascript:

var Employee = function(name, salary) {
  Person.call(this, name);
  this.name = name;
  this.salary = salary;
}
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
Employee.prototype.doWork = function() {
  alert('working!');
}

How about creating a Class and a super function so, that we could rewrite the previous code like this:

var Employee = Class({

  extends: Person

  constructor: function(name, salary) {
    super(name);
    this.salary = salary;
  }

  doWork: function() {
    alert('working!');
  }

});

The usage would be more or less analogous to ECMAScript 6 class:

class Employee extends Person {
  constructor(name, salary) {
    super(name);
    this.salary = salary;
  }

  doWork() {
    alert('working!');
  }
}

It still takes a some time until every browser runs ECMAScript 6, so why not use such shorthand for class declarations? Would this have any real drawbacks? Are there any libraries doing this?

Was it helpful?

Solution

It still takes a some time until every browser runs ECMAScript 6…

if you compile ES2015 code to ES5 with Babel, you can write it that way now anyway. No need for an awkward intermediary.

Would this have any real drawbacks?

A third syntax that attempts to mimic new features without actually being compatible with new features has the problem of proliferating unnecessary standards.

Are there any libraries doing this?

Not exactly; as I mentioned previously, Babel allows code to be compiled from one flavor of ECMAScript to another. I don't know of any intermediary frameworks, but I imagine it's likely that such things already exist in some form.

Licensed under: CC-BY-SA with attribution
scroll top