Search code examples
javascriptnodes

Can I use a function expression as class method in javascript?


I am looking forward about a concrete question in javascript.

I would like to use a function expression as a class method, but I don´t know if it is possible. I try to look any documentation about it but I didn´t find... This is an example:

class TourIdentifier extends HttpClient {
   constructor(baseURL, langCode, ...attr) {
       super({
            baseURL,
            headers: {
            lang: langCode
       }
       });

      this.model.init(...attr);
    }

    model =  function init(...attr) {
    this.tours_identifiers_identifier   = attr[0];
    this.tours_id                       = attr[1];
    this.lang_code                      = attr[2];
    this.tours_id_                      = attr[3];
    this.tours_identifiers_id           = attr[4];
    }

...

I know there are many ways to do this, but I just have this question, and I hope that anyone with more experience than me in JS can share they knowledge.

I appreciate your comments!

Best regards!


Solution

  • This is everything you need to know about method definition in classes MDN, but here is some of my explanation:

    Basically you are trying to define a method in a class(which requires giving this method a name) and then assign a named function to it. This will work, but you won't be able to call the method of the class using the function's name, but you will be able to do it using the method's name.

    Imagine you have a object and a separate function:

    function func() {return 'Hello'}
    
    const obj = {};
    

    And you want to assign the function to one of the object's properties you will do:

    obj.myFunction = func;
    

    And from now on you are going to call the function from the object like this:

    obj.myFunction();
    

    But of course we can assign the function at the object's declaration:

    function func() {return 'Hello'};
    
    const obj = {
        myFunction: func
    }
    

    And you are still going to call the function form the object like this:

    obj.myFunction();
    

    And of corpse you can declare the named functioning in the object's declaration:

    const obj = {
        myFunction: function func() {return 'Hello'}
    }
    

    And you are still going to call the function form the object like this:

    obj.myFunction();
    

    So I hope you see where I'm going.... the same thing can be applied to classes, as we know they are just sugar syntax :) In short this is possible, but the name of the function won't be useful.

    class foo {
        constructor() {
        //something
      }
      
      method = function init() {
        console.log('init 1');
      }
    }
    
    const fooInstance = new foo();
    
    fooInstance.method();