在 stub Component 的一個方法時,發現這個方法沒在 prototype 上。研究了下編譯后代碼發現出一些貓膩,同時也引起思考:對于 React.Component 方法,如何優雅的去綁定 this。
- 問題現象
class Demo extends React.Component {
constructor(props) {
super(props);
this.method1 = this.method1.bind(this);
}
method1() {}
method2 = () => {};
}
method1
和 method2
,分別使用 bind函數 和 箭頭函數 兩種方式綁定 this
。
雖然在程序運行時大多數場景沒有問題,而且經常會使用箭頭函數綁定。但是這兩種聲明方式還是有差異的。
- 查找根因
使用官網的 create-react-app 轉換代碼發現,在 Demo.prototype
上只有 method1
沒有 method2
。
var Demo = function (_React$Component) {
_inherits(Demo, _React$Component);
function Demo(props) {
_classCallCheck(this, Demo);
var _this = _possibleConstructorReturn(this, (Demo.__proto__ || Object.getPrototypeOf(Demo)).call(this, props));
_this.method2 = function () {};
_this.method1 = _this.method1.bind(_this);
return _this;
}
_createClass(Demo, [{
key: 'method1',
value: function method1() {}
}]);
return Demo;
}(__WEBPACK_IMPORTED_MODULE_0_react___default.a.Component);
method2
是在Demo
的構造方法內動態添加的;而method1
通過_createClass
方法被聲明被聲明在prototype
上。
_createClass
內部一段代碼如下
if (protoProps) defineProperties(Constructor.prototype, protoProps);
- 疑問:那種好?
ES2015的 class
只是一個語法糖而已,最終還是通過原型等方式實現。所以方法使用prototype
方式聲明會更好些。
同時也意味著需要使用 bind
方法綁定this
。