在 stub Component 的一個方法時,發(fā)現(xiàn)這個方法沒在 prototype 上。研究了下編譯后代碼發(fā)現(xiàn)出一些貓膩,同時也引起思考:對于 React.Component 方法,如何優(yōu)雅的去綁定 this。
- 問題現(xiàn)象
class Demo extends React.Component {
constructor(props) {
super(props);
this.method1 = this.method1.bind(this);
}
method1() {}
method2 = () => {};
}
method1 和 method2,分別使用 bind函數(shù) 和 箭頭函數(shù) 兩種方式綁定 this。
雖然在程序運行時大多數(shù)場景沒有問題,而且經(jīng)常會使用箭頭函數(shù)綁定。但是這兩種聲明方式還是有差異的。
- 查找根因
使用官網(wǎng)的 create-react-app 轉(zhuǎn)換代碼發(fā)現(xiàn),在 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的構(gòu)造方法內(nèi)動態(tài)添加的;而method1通過_createClass方法被聲明被聲明在prototype上。
_createClass內(nèi)部一段代碼如下
if (protoProps) defineProperties(Constructor.prototype, protoProps);
- 疑問:那種好?
ES2015的 class 只是一個語法糖而已,最終還是通過原型等方式實現(xiàn)。所以方法使用prototype方式聲明會更好些。
同時也意味著需要使用 bind方法綁定this。