I am using the javascript inheritance helper provided here: http://ejohn.org/blog/simple-javascript-inheritance/
I have the following code, and I have problem accessing the inherited property or function from a closure within a subclass as illustrated below. I am new to OOP javascript code and I appreciate your advice. I suppose within the closure, the context changes to JQuery (this variable) hence the problem. I appreciate your comments.
Thanks,
-A
PS – Using JQuery 1.5
var Users = Class.extend({
init: function(names){this.names = names;}
});
var HomeUsers = Users.extend({
work:function(){
// alert(this.names.length); // PRINTS A
// var names = this.names; // If I make a local alias it works
$.map([1,2,3],function(){
var newName = this.names.length; //error this.names is not defined.
alert(newName);
});
}
});
var users = new HomeUsers(["A"]);
users.work();
thisin the inner functionis not the same as
thisin the outer function.There are many ways that people work around this:
Store a reference to outer function’s
thisas another variableAs you see,
thatis being used instead ofthis.Use jQuery’s
$.proxyWhat
$.proxydoes is it creates another function that calls the function you passed in (in this case, the inner function), but explicitly set the context of the function (this) to the second arguments.Use Function.prototype.bind
It works just like jQuery’s
$.proxy, but in this one, you call thebindmethod of the function.It isn’t supported on all browsers, but there is a JavaScript implementation of Function.prototype.bind on MDC. You can use it.
thisin a confusing keyword, and if you want to learn more aboutthis, then look at this.