0

What is the best way to create a function with a specified object as prototype in Javascript? For ordinary objects, you can just use Object.create(). However, this obviously won't create a function. So far, the only way I've found is to define a function normally and then call Object.setPrototypeOf(), but setPrototypeOf is considered to be evil and bad for performance. Is there any alternative?

Antimony
  • 37,781
  • 10
  • 100
  • 107
  • _`setPrototypeOf` is considered to be evil and bad for performance_. What? – ibrahim mahrir Oct 21 '17 at 00:33
  • @ibrahimmahrir Just look at the scary warnings on MDN for instance – Antimony Oct 21 '17 at 00:36
  • 2
    Are you trying to create a constructor function that creates objects with a certain prototype, or are you trying to set the prototype of the function itself? (if it's option 2, why would you need to do that?) – 4castle Oct 21 '17 at 00:37
  • Yes, the later. – Antimony Oct 22 '17 at 01:40
  • I'm curious why you want to do this? I can't think of any benefits to giving a function a different prototype, but it does have downsides in that you'd lose the normal function prototype's `.bind()`, `.call()`, etc. methods. If you feel you *must* do this, just use `Object.setPrototypeOf()`, which may not be great for performance but certainly isn't "evil". – nnnnnn Oct 22 '17 at 02:43
  • The main motivation is that it is the only way to inherit static properties when simulating subclasses without es6 classes. – Antimony Oct 22 '17 at 04:01

0 Answers0