Search code examples
javascriptfirebaseclassoopgetter-setter

How to declare a function with the same name as a property in class name in javascript?


I have come across this from working with Google Firebase Authentication and Firebase Firestore. You can access the variable and the function of their classes with the same name, for example:

//To authenticate:
firebase.auth().signInWithEmailAndPassword()

//Or to access a value
firebase.auth.Auth.Persistence.SESSION

Notice how they can use both firebase.auth and firebase.auth(). When I try to see if I can do it, it throws an error:

class foo {

    public bar;

    constructor() {
        this.bar = 'Bar!'; //Expecting 'Bar!' when run foo.bar()
    }

    //However, it throws an error here, as bar was already defined
    bar() {
        return 'Function bar() was called';
    }

}

I even tried looking into setter and getter since they also can recognize whether it was foo.bar or foo.bar() that got called, but setter does not accept a returned value.

How could I do what the Firebase Team is doing? How did they work out this magic?


Solution

  • Man you have to notice the equivalent to firebase style of your class should be like following, you just did it wrong.

    class foo {
    
        constructor() {
            this.bar.bar = 'Bar!';
            // instead of this.bar = 'Bar!';
        }
    
        bar() {
            return 'Function bar() was called';
        }
    
    }
    

    However. If you must set to '.bar' as a normal value then get .bar back as a function, you can go with getter/setter. Just it doesn't make much sense to me.

    class foo {
    
        constructor() {
            this.bar = 'Bar!';
        }
    
        barFunc() {
          'Function bar() was called';
        }
    
        get bar() {
          return this.barFunc;
        }
    
        set bar(value) {
          this.barValue = value;
        }
    
    }