4

using ES2015, I want to extend Function class and use its instance as a callable function.

class Foo extends Function {
  // how to wite behavior?
}

let foo = new Foo();

foo();
foo.call();
// this is callable, but no behavior defined

How can I let foo have its specific behavior in its declaration?

1
  • "I want to extend Function" Why? What's the underlying goal? Commented Mar 1, 2016 at 11:54

2 Answers 2

3

The Function constructor accepts arguments:

new Function ([arg1[, arg2[, ...argN]],] functionBody)

That being the case, you'd call super with appropriate arguments:

// SNIPPET ONLY WORKS ON ES2015-ENABLED ENVIRONMENTS
"use strict";
class Foo extends Function {
  constructor() {
    super("a", "console.log(a);")
  }
}

let foo = new Foo();

foo("one");
foo.call(null, "two");

Now, it's a pain to write JavaScript code inside a string literal, and the code within the function text is evaluated at global scope so we can't do something like defining the actual function within the constructor and calling to it from the function text. So this is of limited use. But...

Sign up to request clarification or add additional context in comments.

Comments

2

The original function constructor takes a string as an argument, so the following should work for you if you didn't override the constructor:

const foo = new Foo("console.log(42)");
foo(); // outputs 42.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.