3 ms·
No but this is still bound at call time, so `self` will be foo in foo.play() just as this, so that's basically the same thing + a standard variable assignment t
by marcusf 14y ago
No but this is still bound at call time, so `self` will be foo in foo.play() just as this, so that's basically the same thing + a standard variable assignment to get the setTimeout working.
On a sidenote, I'm trying to get away from using self, and do object.bind in all my setTimeouts. To my mind, it leads to much cleaner code.
- jQueryIsAwesome 14y agoBind is not supported in IE8 and older versions. You could use the underscore library or another one that haves a cross-browser bind method.
- marcusf 14y agoFor my particular use case, IE8 is not an issue, but sure, a shim is like three lines, and we did use that before (when IE8 was an issue).
- pixie_ 14y agoobject.bind doesn't look very clean compared to using self.
- jQueryIsAwesome 14y agoAnd in JS is really easy to create an abstraction for this issue: function wait(o){ return setTimeout(function(){ o.action.call(o.this) },o.delay*1000) } To use it like this: wait({ action : function(){ console.log(this) }, delay : 1, this : this });
- pixie_ 14y agoIf you're writing abstractions to avoid bad language features, maybe you shouldn't be using bad language features in the first place.
- marcusf 14y agoThe nice thing about it is that it allows you to break out of nesting hell while still being prototyped... e.g. window.setTimeout(this.foo.bind(this), baz); Since .bind is essentially currying, you could imaginably do window.setTimeout(this.foo.bind(this, bar), baz) as well, if foo is dependent on bar (timing out a request `bar' or something like that).