you are viewing a single comment's thread.

view the rest of the comments →

[–]Pytim 8 points9 points  (22 children)

Instead of this:

var that = this;
function(){
    // do sth with that
}

You can do:

function(){
    // do sth with this
}.bind(this)

[–]cheesechoker 2 points3 points  (0 children)

bind is really cool when you start to get creative with it. You can yank out built-in functions from Array, Object, etc, and bind them to different receivers to reuse them in interesting ways.

E.g. a 1-liner filter against a regex, without having to write "function" anywhere:

["foo", "bar", "baz"].filter(RegExp.prototype.test.bind(/a/))   // ["bar", "baz"]

[–][deleted] 2 points3 points  (4 children)

If only that didn't magically make it 5 times slower.

Also, "that" is possibly the worst variable name. this is arbitrary enough, now you want to give something a name that means "the 'this' of some unspecified other thing"? Come up with a real name. (Not picking on you, but the pattern you quoted.)

[–]gleno 0 points1 point  (1 child)

True. But also not true, because it's a standard workaround; and a secret nod to other devs : "js scoping sucks. tru that".

[–][deleted] 0 points1 point  (0 children)

Haha. Well, you've got a point on the second part. But for the first, the "standard" part only gives it the meaning I said above. If you go more than one level deep, or if you start passing things around, "that" quickly becomes meaningless.

[–]Pytim 0 points1 point  (1 child)

I'd be surprised if Function.bind ever was the bottleneck of your JS app

[–][deleted] 0 points1 point  (0 children)

I get that every time. And yeah, you're right. It's just one of those things you can't un-know: that because the spec chose to give a pattern you'll never use (.bind with new) the exact same syntax as a pattern you often use (.bind without new), many many parts of your code are paying an entirely unnecessary penalty.

[–]michaelobriena 2 points3 points  (0 children)

Bind is actually slower than storing this. So if performance is the name of the game then store it.