rwaldron / idiomatic.js

Principles of Writing Consistent, Idiomatic JavaScript
Other
24.83k stars 3.48k forks source link

Question regarding 6.B.3 #125

Closed iqrow closed 10 years ago

iqrow commented 10 years ago

"As a last resort, create an alias to this using self as an Identifier. This is extremely bug prone and should be avoided whenever possible."

Would you mind explaining, or pointing me in the direction of some resources on why this is extremely bug prone please?

I'm currently exploring existing coding standards and sometimes they lack reasons/explanation as to why.

I did some googling and could only find information on the this but not why aliasing it can be bug prone.

Thanks.

serbanghita commented 10 years ago

I think I've responded to this already at https://github.com/airbnb/javascript/issues/81 Check it out

iqrow commented 10 years ago

Thanks for the link. I read through it, and it brings some interesting points to the discussion. Obviously blunt variables like 't' aren't useful and I was (up until now) unaware of window.self so I'm glad I've been enlightened.

I'd adopted the jQuery practice of var self = this as to me, this read very idiomatically, knowing that my module was referring to itself in a scope. But I'm thinking of switching back to what we used to use which is var that = this.

Ultimately though, we're quibbling about what to and what not to alias our this with. Be it, t, self, _this or that. But that's not my question.

My question is why aliasing is inherently bug prone regardless of what we use an alias. Unless of course the answer is because of the likelihood of the alias colliding with an existing one.

mnquintana commented 10 years ago

I have the same question as @iqrow - why is this necessarily extremely bug prone? I have also tried searching for any resources that explain this, but haven't come across any.

rwaldron commented 10 years ago

When a this-alias binding is created and then used in some callback (or event handler), the reference that it points to becomes effectively impossible to garbage collect because the callback may or may not have side-effects which leak the reference.

iqrow commented 10 years ago

Ah, interesting - I closed this because it had been open for so long that I'd forgotten about it entirely until stumbling back across it. Thanks for the answer!