7 ms·
I think understanding "this" in javascript is actually much easier if you have had exposure to C++ function tables. With that knowledge in hand, it immediately
by dsp1234 10y ago
I think understanding "this" in javascript is actually much easier if you have had exposure to C++ function tables.
With that knowledge in hand, it immediately becomes obvious that:
bar.baz = function(){console.log(this.X)}
var foo = bar.baz;
foo();
Is not going to result in a console log of bar.X. "foo" is a pointer-to-member function, and executing it without a context is going to cause problems. The biggest in javascript as compared to c++ is that javascript will always provide the hidden "this" (even if it's the global context), whereas c++ will always bail out if you don't provide it with a proper context.
But really, understanding that behind the scenes, member function calls change:
A.B(C)
into
B(A, C)
clears up a lot of "this" mistakes, and also enlightens the proper usage of function.bind.
- shp0ngle 10y agoOnce I started using arrow notations, I stopped worrying about `this`. Whenever I need to export class function, I do var foo = () => bar.baz() , no more worrying, no need to understand what the hell bind does exactly. Also with the ... notation, I stopped worrying about .call and .apply. So I can write var someArray = [a,b,c] var foo = () => bar.baz(...someArray) and so on.