Search code examples
javascriptecmascript-6ecmascript-next

Class methods - which one to use and when?


There seems to be two different way to define a method within a class.

class Foo {
    handleClick = e => {
        // handle click
    }
    // and
    handleHover(e) {
        // handle hover
    }
}

My question is what is the difference between the two?

When transpiled, they give decidedly different results:

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Foo = function () {
    function Foo() {
        _classCallCheck(this, Foo);

        this.handleClick = function (e) {}
        // handle click

        // and
        ;
    }

    _createClass(Foo, [{
        key: "handleHover",
        value: function handleHover(e) {
            // handle hover
        }
    }]);

    return Foo;
}();

But I can't seem to discern what the differences are. Is it a binding issue?

Thanks!


Solution

  • class Foo {
        handleClick = e => {
            // handle click
        }
    }
    

    is not ES6. It's a proposal for a future version of ES.

    The equivalent ES5 code to your example would be

    class Foo {
        constructor() {
            this.handleClick = e => {
                // handle click
            }
        }
        // and
        handleHover(e) {
            // handle hover
        }
    }
    

    and the equivalent ES6 code to your example would be

    function Foo() {
      this.handleClick = function(e) {
          // handle click
      }.bind(this);
    }
    
    Foo.prototype.handleHover = function(e) {
        // handle hover
    }
    

    So basically handleClick is autobound to the instance, which can be useful for event handlers, but it comes at the cost of creating a new function for every instance.

    For more information see