3 ms·
There is literally NO substitute for either call or apply as they are low-level JS primitives. Arrow functions can go a long way toward handling .bind() scenari
by hajile 5y ago
There is literally NO substitute for either call or apply as they are low-level JS primitives. Arrow functions can go a long way toward handling .bind() scenarios, but I believe there are situations where you must still use .bind() to prevent constantly creating new functions (and the related garbage).
- bluepnume 5y agoShow me some code you can only write using either call, apply, or bind.
- wruza 5y agoAnything that substitutes ‘this’ but doesn’t want to put a function into that object. const {filter} = [] class Foo { less() { return filter.call(this, sometest) } } There is no way to closure it somehow without (temporarily) modifying an instance of Foo. (The next obvious question is “why” and the answer is “metaprogramming”.)
- bluepnume 5y agoI would rather re-implement `filter` in a way that is specific to `Foo`, than to attempt to use an array method on my class.
- wruza 5y ago.bind() does create a new function, though it has far less “slots” than a regular one. It doesn’t modify the original function. The spec doesn’t specify anything beyond that, afair, and if binds aren’t cached in some way (easy to check with === or roll up your own cachedBind()), GC barely can make any benefit out of collecting slightly smaller objects (but the interpreted part of a runtime may still process bound functions a little faster than closures doing the same thing). As of source code or p-code or by whatever structure {<code>} body is represented inside, it is always* static for all closures, so there is no overhead apart from a closure itself between: function foo() {<code>} // func for (;;) foo() and let i = 0 for (;;) { let j = 0 function foo() {i++; j++; <code>} // closure foo() } Because {…<code>} is a singleton in both snippets. * of course jit may blur this distinction a lot, but that’s unrelated