0

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?

5
  • Well, TypeScript cross-compiles to EcmaScript 5. TypeScript has what you want and more. Sep 13, 2016 at 16:38
  • Note that the latest versions of Chrome, Firefox, Opera and Edge already support the vast majority of ES6. See kangax.github.io/compat-table/es6 Sep 13, 2016 at 17:11
  • Plus there are old libraries from before ES6 that already did what you describe
    – Izkata
    Sep 13, 2016 at 18:37
  • @Izkata Just out of curiosity, how are the called? Sep 14, 2016 at 14:12
  • The reason for why is because if you are like me and you want max speed and minimum size, then look to the past, not the future. A feature that has been around since JS 1.0 is variables. Specifically, variables can be utilized as numerical enumerations which give extra clarity and unbelievable speed to your code when the constant variables are inlined with closure compiler. For example, var ENUM_FOOD_APPLE=0, ENUM_FOOD_PEAR=1, ENUMLEN_FOOD = 2, myArr = ["yum","yuck"]; console.log(myArr[ENUM_FOOD_APPLE], myArr[ENUM_FOOD_PEAR])
    – Jack G
    Mar 22, 2018 at 19:47

1 Answer 1

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.