by dmitriid · 7y ago · 0 comments
So they bolted on an incompatible thing that hides prototypes and is confusing to devs:
class C {
y = 10;
// this fine. "methods" defined as class properties
// have access to proper `this` due to how class properties work
// and scoping rules
x = () => if(this.y > 10) this.y = 10;
constructor() {
// if you don't bind `this`, `method()` will not have access
// to `this`
this.method = this.method.bind(this)
}
method() {
// will refer to a wrong `y` if `this` isn't bound
// in the constructor
this.y++;
}
} const instance = new C();
for(let i = 0; i < 20; i++) {
instance.method();
}
instance.x()
If you don't bind `this` to `method` in the constructor, when you call `instance.method()`, `this` will be whatever (window, IIRC).Don't believe me? Try a more complex example like React's event handling with `this.setState()`: https://reactjs.org/docs/handling-events.html
> Why would I put this.y = 10 in the constructor?
Because that's how you initialize attributes of an object instance in JS, in January 2019.
I don't believe this code does what you think it does. Even if your definition of `x` generated an attribute of instances of C, using an arrow function would defeat your apparent intention: arrow functions take their surrounding lexical scope's `this`, which in this case is the class, not any instance you define from the class.
> If you don't bind `this` to `method` in the constructor, when you call `instance.method()`, `this` will be whatever (window, IIRC).
Simply not the case, as another commenter has pointed out: `instance` in your loop is definitely `method`'s `this`, and not `window`.
Ah, true. I keep forgetting class fields are not standardized yet since eve ryone is using them anyway just because they are so damn handy.
> Even if your definition of `x` generated an attribute of instances of C, using an arrow function would defeat your apparent intention: arrow functions take their surrounding lexical scope's `this`, which in this case is the class, not any instance you define from the class.
For the current implementations of class fields this works. If they change that behaviour, what good are classes?
Now onto bound methods: you are wrong in your code example; `instance.method()` does not require `method` to be a bound method; an unbound function is just fine. The code is equivalent to `instance.method.call(instance)`, which (for an unbound function) calls it with `instance` as its context. The problem is when, at call time, you don’t access the function as a property on another object, like this:
const fn = instance.method;
fn();
Or `(1, instance.method)()`. Then you need to worry about what the context will be (in strict mode, it’ll be `undefined`, and so any property access on it will immediately blow up, which is good).Bound methods are created by Function.prototype.bind, or by arrow functions.
In what I will choose to call “normal code”, it’s somewhere between very rare and not particularly common to need to bind a function manually. Understand this: React is not normal code. React was designed in a distinctly unusual way (they invented an rather substantial language extension to achieve it!), and although that language and design has turned out quite well in most ways, it also has some exceptionally nasty weaknesses and rather annoying ergonomic troubles; and the need to bind functions is one of them. This is not JavaScript’s fault, but is because React has gone for a VDOM approach that (I think?) requires object identity in such cases, for reasons of efficiency. In search of one form of ergonomics, they damaged another form that others don’t have to worry about very often at all. Such is life, and the nature of tradeoffs.
Most of the trouble with needing bound functions happens with event handling. (Certainly not all, but most, in my experience.) In non-React, non-VDOM-based code, you might be doing something like this:
const foo = document.createElement('foo');
foo.addEventListener('bar', event => {
…
});
… and that’d be perfectly fine there. And a whole lot more efficient at runtime than React, I might add. * If you needed `this`, then the arrow function got it for you automatically.Sometimes you would want a separate function to designate the event handler, and so you may want to call bind(), but it’s also just as likely that you’ll want to keep Event out of that method, and just do `foo.addEventListener('bar', event => this.handleBar(event.detail))`. Maybe, maybe not.
From your earlier example: be careful with your `x = () => …` instead of `x() { … }`, because that instantiates a new function for every instance of the object, which is very inefficient for memory consumption and performance. Binding a method from the prototype is much more efficient (though still to be avoided where unnecessary).
The most interesting approach to resolving this binding problem that React causes lies in the decorators proposal (currently at stage 2). https://github.com/tc39/proposal-decorators/blob/master/boun... is all about a @bound decorator.
* Just be careful with adding event listeners, and remember to use bubbling.
Ah, true. I looked at the code, and was blind to it :)
> Understand this: React is not normal code. React was designed in a distinctly unusual way
There's nothing unusual about React.
> (they invented an rather substantial language extension to achieve it!)
That "extension" is nothing but function calls [1] [2]
Quote: "Each JSX element is just syntactic sugar for calling React.createElement(component, props, ...children). So, anything you can do with JSX can also be done with just plain JavaScript."
> This is not JavaScript’s fault
It is entirely Javascript's fault. That is, it's the fault of its haphazard development with reckless disregard to any long-term planning.
Classes are deliberately designed to look and behave, for the most part, like classes in C++-like languages. So they hid the whole prototype chain away behind the class keyword... But it's still there, and you have to be always consciously aware of it.
As for the rest of your example, and how "you would rarely need to bind methods", well even the class fields proposal binds methods in its examples. So much for "rare" [3] And with quite a few people using WebComponents which are also class-based, well... Just a literally the first example I found: [4]
And of course class fields will behave like class fields in C++-like languages will behave. Unlike methods. Because reasons.
And of course, the "solution" to that is to throw in another half-baked solution in the form of a decorator. Which will take another several years to go through the standardization stage. ¯\_(ツ)_/¯
[1] https://reactjs.org/docs/jsx-in-depth.html
[2] https://reactjs.org/docs/react-without-jsx.html
[3] https://github.com/tc39/proposal-class-fields
[4] https://github.com/elmsln/lrnwebcomponents/blob/master/eleme...
And available now as: https://babeljs.io/docs/en/babel-plugin-proposal-class-prope...
The fact that arrow functions declared as class fields get access to the proper `this` in the class instance is just a happy(?) coincidence with its own downsides. For example, class fields can't be inherited in the child class. So this adds a yet another layer of confusion for devs.
And as you see in the example at the link you provided, you still need to `.bind(this)` the actual methods.