react.js v0.13 RC – statics are no longer autobounded

このエントリーをはてなブックマークに追加

Static methods (defined in statics) are no longer autobound to the component class

Components have statics and members defined in statics can be accessed directly via the component class. (refer to the official link for examples)

Before react.js v0.13rc, members defined in statics were autobound to the component which means ‘this’ was tied to the component. This is better explained by the JSFiddle below.

MyComponent has message:string and staticMethod:function defined in statics. Inside the staticMethod, ‘this.message’ is called. The point here is what ‘this’ is bound to. Versions prior to v0.13rc ‘this’ is bound to MyComponent which means ‘this.message’ is the same as MyComponent.message, and therefore, the value is ‘Hello’. (Why not ‘Hey!’ in spite of the ‘call’ function using the ‘caller’? Because ‘this’ is already bound to MyComponent and as far as I know, a method bounded cannot easily be overwritten)

Starting from v0.13rc, this magical autobound is not going to happen anymore. Hence the code above will end up outputting ‘Hey!’, not ‘Hello’.
This is because staticMethod’s caller becomes the ‘caller’ object.(not MyComponent). And the ‘caller’ object has message:’Hey!’ as his member.

I wonder why they made this change. Is it because i becomes more flexible??? Or because ES6 will let arrow functions autobind ‘this’??? That still remains a question for me.

Written on March 1, 2015
このエントリーをはてなブックマークに追加