最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ecmascript 6 - Calling class instance as a function in JavaScript - Stack Overflow

programmeradmin1浏览0评论

Assuming I have a class

class foo {
  constructor() {
    this._pos = 0;
  }
  
  bar(arg) {
    console.log(arg);
  }
}

const obj = new foo();

Assuming I have a class

class foo {
  constructor() {
    this._pos = 0;
  }
  
  bar(arg) {
    console.log(arg);
  }
}

const obj = new foo();

How do I make it possible to call:

let var1 = obj('something');
Share Improve this question asked Mar 14, 2018 at 13:59 intellionintellion 1,43713 silver badges27 bronze badges 8
  • 3 You can't "call" a plain object; what would that even mean? What code would run? – Pointy Commented Mar 14, 2018 at 14:02
  • Do you want to call bar method of foo class or what? Please clarify. – standby954 Commented Mar 14, 2018 at 14:02
  • What you have and what you want to do don't go with each other. You have an instance of a class (an object) and you want to invoke the object as a function. – Scott Marcus Commented Mar 14, 2018 at 14:03
  • 3 meta.stackexchange./questions/66377/what-is-the-xy-problem – Yury Tarabanko Commented Mar 14, 2018 at 14:04
  • 1 Technically you could extend built-in Function constructor using class Foo extends Function. Demo But you can doesn't mean you should. :) – Yury Tarabanko Commented Mar 14, 2018 at 14:09
 |  Show 3 more ments

1 Answer 1

Reset to default 9

You can make a callable object by extending the Function constructor, though if you want it to access the instance created, you'll actually need to create a bound function in the constructor that binds the instance to a function that is returned.

class foo extends Function {
  constructor() {
    super("...args", "return this.bar(...args)");
    this._pos = 0;
    return this.bind(this);
  }
  
  bar(arg) {
    console.log(arg + this._pos);
  }
}

const obj = new foo();

let var1 = obj('something ');

发布评论

评论列表(0)

  1. 暂无评论