Default handler for a functional class in JavaScript

坚强是说给别人听的谎言 提交于 2021-01-28 10:58:30

问题


I wanted to know if it is possible to have a functional class have a default call method. Let me elaborate.

function Foo(){
  /*some logic*/
  Foo.prototype.aletUser = function alertUser(message) {
    alert(message);
  }
}

Assume that the code above is my functional class (if my naming for the above structure is wrong please tell me), and i instantiated one of this structure.

let param = new Foo();

Now, i wish to call the following and hope for it to call my prototype Foo.alertUser

param('Hey There')

How can this be achieved? Thanks in advance.


More insight behind my approach

I am working with React Native and i wish to have param('Hey There') use a hook inside the function but i am out of ideas, i know how to make it work with JavaScript classes, but unfortunately hooks can not be called inside class components.


回答1:


Answering the question you actually asked, it's possible but probably not a good idea. One way to do it is to have new Foo create a function and then change its prototype (which is normally not a good idea), like this:

function Foo() {
    // Create a function, the change its prototype to
    // `Foo.prototype` and return it
    const retval = function alertUser(param) {
        console.log(param);
    };
    Object.setPrototypeOf(retval, Foo.prototype);
    return retval;
}
// Make `Foo.prototype` use `Function.prototype` as its prototype
Foo.prototype = Object.create(Function.prototype);
Foo.prototype.constructor = Foo;


const param = new Foo();
param("Hi there");

But, again, that's probably not a good idea, for a couple of reasons:

  • Changing an object's prototype can deoptimize the JavaScript engine's implementation of it. Now, it may not matter for what you're using this for, it depends on whether it's critical path (and the degree that the deoptimization is noticeable), so it's certainly an option.

  • You've said you're trying to do this so you can use a hook in a class component. As I said in a comment, that's probably not going to work and even if it does, it's probably not your best solution

I would step back and say if you find yourself wanting to call a hook from a class component, your best bet is to either:

  1. Build class-based functionality equivalent to the hook and don't use the hook, or

  2. Change the class component to a functional component so you can use the hook in the normal way



来源:https://stackoverflow.com/questions/64086992/default-handler-for-a-functional-class-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!