2 ms·
What You Need To Know About JavaScript Scope
- pkulak 17y agoI moved over to jQuery from Prototype and I've been missing an easy way to bind scope. Does anyone know if jQuery has any helpers like Prototype's bind()?
- sunkencity 17y agobecause of the chainable elements it's not as crucial to have this in jquery as in prototype. I don't think there's a helper for that in jquery (so does also this article say).
- natrius 17y agoWhere do you find yourself needing such a thing? I never rely on `this` unless I'm inside of a $.each call because it's so implicit and error prone. If you're trying to use bind with a function that you've written, I'd say just rewrite it to not use `this`. It'll make it clearer. If it's a function from some library, complain, then do something similar to the last example from the article, though it seems more complicated than it needs to be.
- seasoup 17y agoYou bind scope by setting the variable this to a locally scoped variable before your function call: var foo = { 'bar': function () { var that = this; $(selector).each(function () { alert(that); } } } or else in the cases of objects like the above where there is only one instance of the object you can refer to foo by name. var foo = { 'bar': function () { $(selector).each(function () { alert(foo); } } } Events are a bit trickier as they get set on DOM elements and the variable declared in front of it with local scope cannot be accessed from within. var foo = { 'bar': function () { var that = this; $(selector).click(function () { alert(that); // doesn't work! } } } You can get around this by passing a variable into the function called by the event. var foo = { 'bar': function () { var that = this; $(selector).bind('click', {'that': this}, function (e) { alert(e.data.that); //accessed via e.data } } }
- axod 17y agovar boundfunction = function(c) {return function(){ c.doSomething()}}(this); Learning javascript > learning a js lib.