【问题标题】:Class methods - which one to use and when?类方法 - 使用哪一个以及何时使用?
【发布时间】:2017-03-04 06:34:30
【问题描述】:

在类中定义方法似乎有两种不同的方式。

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

我的问题是这两者有什么区别?

在编译时,它们会给出截然不同的结果:

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;
}();

但我似乎无法辨别其中的差异。是绑定问题吗?

谢谢!

【问题讨论】:

  • 只是箭头函数和函数表达式的区别。方法语法只是函数表达式的语法糖。
  • 知道了。谢谢!
  • 我重新打开了这个问题,因为副本在这里并不真正适用。请注意,您的代码不是有效的 ES6。它使用了 ES 未来版本的功能提议。

标签: javascript ecmascript-6 ecmascript-next


【解决方案1】:
class Foo {
    handleClick = e => {
        // handle click
    }
}

不是 ES6。 It's a proposal for a future version of ES.

与您的示例等效的 ES5 代码是

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

与您的示例等效的 ES6 代码将是

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

Foo.prototype.handleHover = function(e) {
    // handle hover
}

所以基本上handleClick 会自动绑定到实例,这对于事件处理程序很有用,但它的代价是为每个实例创建一个新函数。

有关详细信息,请参阅

【讨论】:

  • 哦,有趣。我没有注意到我在我的 Babel REPL 中勾选了stage-2。取消勾选它会引发语法错误,这是有道理的。所以它本质上是“自动绑定”,但每当调用new 时都会创建一个新函数。现在明白了,谢谢!
  • 请注意,“自动绑定”是使用箭头函数的结果,而不是使用“类字段”。 IE。 handleClick = function(){} 会在构造函数中定义函数,但不会自动绑定。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-13
  • 2016-08-11
  • 2011-01-25
  • 1970-01-01
  • 2014-06-04
  • 2011-06-07
  • 1970-01-01
相关资源
最近更新 更多