0

In es5 you can do it by setting a prototype to an existing function but how would you go about this with ES6 classes

//// ES5
function existingFn = function () {
    // does something
};

function MyClass () {
    // constructor stuff
};

MyClass.prototype.newFn = function () {
    // …
};

MyClass.prototype.existingFn = existingFn;

//// ES6
class MyClass {
    constructor() {}

    newFn() {
        // …
    }

    // ???????
    // existingFn = existingFn
    // ???????
}
Maruf
  • 890
  • 3
  • 10
  • 21

2 Answers2

1

ECMA-Script 6 class syntax is a syntactic sugar over regular prototype system:

class A {

}

// This is still possible!
A.prototype.doStuff = function() {

};

var existingFn = function() {};

A.prototype.existingFn = existingFn;

var instance = new A();
instance.existingFn();
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
  • 2
    Keep in mind for the future, it's slightly more complicated: `Object.defineProperty(A.prototype, 'existingFn', {configurable:true, writable: true, enumerable: false, value: existingFn});`. Your example _could_ fail if there were a parent class that had this method, and this was overriding it, and the parent property was a getter/setter or non-writable. – loganfsmyth Oct 10 '15 at 19:43
  • @loganfsmyth I was trying to provide a solution for OP's simple scenario. – Matías Fidemraizer Oct 11 '15 at 08:13
0

"Es6 way" of defining properties is using constructor

class MyClass {
  constructor() {
    this.existingFn = existingFn;
  }
}
Lesha Ogonkov
  • 1,218
  • 8
  • 20
  • @MatíasFidemraizer Well, it's the only way i have find (without using prototype). I'm personally prefer using good 'ol prototype. http://stackoverflow.com/questions/22528967/es6-class-variable-alternatives – Lesha Ogonkov Oct 11 '15 at 10:36