4 ms·
Of course, taking the method out of the object will produce a different result. But if you are doing something weird like that you should know what you are doin
by jQueryIsAwesome 14y ago
Of course, taking the method out of the object will produce a different result. But if you are doing something weird like that you should know what you are doing.
- epidemian 14y agoI don't think it's _that_ weid considering JS is a language where functions are perfectly normal values. Someone unfamiliar with the semantics of "this" in JS might expect that: player[playing ? "play" : "pause"]() (a not-so-weird JS pattern) would be the same as: (playing ? player.play : player.pause)()
- jQueryIsAwesome 14y agoIn what other language you have direct access to methods as first class objects to do an immediate execution of a method returned by an execution container (parenthesis in JS) ? I think most people would write it like this: playing ? player.play() : player.pause()
- epidemian 14y ago> In what other language you have direct access to methods as first class objects to do an immediate execution of a method returned by an execution container (parenthesis in JS) ? Not sure if i understand the question. This seems to work in Python: s = "Hello" up = True (s.upper if up else s.lower)() Not that it's a very pythonic piece of code, but it works, and i would expect many other languages support something similar. Anyway, that's tangential. And i wasn't discussion what "most people would" do either. What i was trying to say is that by aliasing "var self = this" you're not automatically immune to the quirks of "this" in JS.
- jpolitz 14y agoIndeed --- Python goes to great lengths to work this way, automatically binding the self argument on method extraction. o.f() Can be decomposed in Python: func = o.f func() JavaScript fails this test, and it's a shame.
- jQueryIsAwesome 14y agoIt's actually a Javascript strength; one that makes it more dynamic. NodeList.prototype.map = Array.prototype.map Just one line and now you can do stuff like: document.querySelectorAll("div").map(function(ele){ return ele.id });
- epidemian 14y agoHo, you beat me to it with the Python reference (see my other comment in this thread) :) I don't know if it's really that bad that JS returns the unbound function when doing `obj.someFunc`, as it is consistent with any other property access: it returns the same thing that was assigned to that key in the object, or at some point in its prototype chain. The really broken behavior, at least for me, is that when doing `var f = obj.someFunc(); f()`, the "this" gets bound to "window" in the f() call, instead of being null, or better yet raising an error whenever referenced, like an undefined variable.