3 ms·
Note that self = this is kind of a legacy hack for binding 'this'. ES5 has Function.bind https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Glo
by mikeryan 12y ago
Note that self = this is kind of a legacy hack for binding 'this'.
ES5 has Function.bind
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- cozuya 12y agoIf you want to call something that increases performance by 50% a hack, feel free, but I'm going to use that hack until that's not the case.
- nkohari 12y agoDo you have a source? I don't understand how a closure over a single variable (this), instead of reassigning the value of the variable in a specific scope, would result in a 50% improvement in performance. Also -- the phrase "50% improvement in performance" itself is kind of dubious, no?
- peter_l_downs 12y agoIt can also be nice when you're writing instance methods on a prototype. for instance: var Person = function(name) { var self = this; self.name = name }; Person.prototype = new function() { var prototype = this; prototype.sayHello = function() { var self = this; return "Hello\n\n-- " + self.name; }; }; var me = new Person('Peter'); console.log(me.sayHello()); Obviously that's a pretty contrived example but it illustrates the idea. It makes it really clear exactly what "this" means at different points in your code. As a bonus, if I had to reference the current context inside of a prototype method, "this" is now available.
- bshimmin 12y agoI don't like `var self` at all and I find there are vanishingly few places where you can't just bind a function appropriately, but one important thing to note, if you do go down this route, is that `self` is an alias for the `window` object, so if you happen to miss out that `var self` assignment at some point, you may get unexpected results. On that basis, if you must do this, I would suggest `var _this`, `var scope` (though that would probably be confusing if you had the misfortune to be using Angular), `var me` (unless you happen to find anthropomorphism distasteful) or... well, anything other than `var self`, really.
- peter_l_downs 12y agoInteresting, I never knew that `self === window` – thanks for bringing that up. I'm not particularly attached to the name, just wanted to show an example where assigning `this` to some local variable is useful.