How to get a link to a class function in ES6?

Sorry if the question is too simple, but I missed something. Just switched the ES5 module, which looked like this:

module.exports = { func1: function(a, b) {...}, func2: function(a, b) {...} }; 

For the ES6 class, which looks like this:

 export default class { func1(a, b) {...} func2(a, b) {...} } 

And all was well: in both cases I could export mod from 'module'; and call mod.func1(a, b) and mod.func2(a, b) .

However, I have a function that gets a module function to call:

 var caller = function(func, val1, val2) { let a = something(val1); let b = something(val2); return func(a, b); }; 

When I call caller(mod.func1, x, y) , I get the desired result with the first implementation, but undefined is not a function with the second.

The mod.func1 returns [Function] in both cases, but obviously something else is returning from the ES6 class.

What am I doing wrong, and how can I get a class function that I can call in another function?

Update: with the second implementation, I forgot to add the instance code:

 import Mod from 'module'; var mod = new Mod(); 
+7
javascript ecmascript-6 es6-module-loader
source share
2 answers
 class MyClass { method(args) {} } 

- short arm for:

 function MyClass() {} MyClass.prototype.method = function(args){}; 

What you are looking for is the static method in the constructor, which in ES {3,5} runs as follows:

 function MyClass() {} MyClass.method = function(args){}; 

and in ES6, the static modifier:

 export default class { static func1(a, b) { /* stuff */ } static func2(a, b) { /* stuff */ } } 

However, you can use short methods even in an object, so using a regular object is generally more clear:

 export default { func1(a, b) {/* stuff */}, func2(a, b) {/* stuff */} } 

Why are constructor methods not available to the constructor?

Because it is not so in ES3 or ES5:

 function MyClass() {}; MyClass.prototype.method = function(args) {}; MyClass.method // undefined var instance = new MyClass(); instance.method // function(args) {} 

Creating an instance is necessary to access prototype methods.

+5
source share

Why did you switch to the class construct (which is a little more than syntactic sugar for the constructor and prototype using methods)? There is no reason not to use the object literal as you did before - you can also use the method syntax:

 export default { func1(a, b) {...}, func2(a, b) {...} }; 

Instead of exporting an object with static methods, it would be wiser to use named export here:

 export function func1(a, b) {...} export function func2(a, b) {...} 

which can be imported with import * as mod from 'module' if you want to use mod as a namespace.

+4
source share

All Articles