Javascript OOP - accessing the inherited property or function from a closure within a subclass -
i using javascript inheritance helper provided here: http://ejohn.org/blog/simple-javascript-inheritance/
i have following code, , have problem accessing inherited property or function closure within subclass illustrated below. new oop javascript code , appreciate advice. suppose within closure, context changes jquery (this variable) hence problem. appreciate 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 // var names = this.names; // if make local alias works $.map([1,2,3],function(){ var newname = this.names.length; //error this.names not defined. alert(newname); }); } }); var users = new homeusers(["a"]); users.work();
this
in inner function
function(){ var newname = this.names.length; alert(newname); }
is not same this
in outer function.
work: function(){ $.map([1,2,3],function(){ var newname = this.names.length; alert(newname); }); }
there many ways people work around this:
store reference outer function's this
variable
work: function(){ var = this; $.map([1,2,3],function(){ var newname = that.names.length; alert(newname); }); }
as see, that
being used instead of this
.
use jquery's $.proxy
work: function(){ $.map([1,2,3],$.proxy(function(){ var newname = this.names.length; alert(newname); }, this)); }
what $.proxy
creates function calls function passed in (in case, inner function), explicitly set context of function (this
) second arguments.
use function.prototype.bind
work: function(){ $.map([1,2,3],function(){ var newname = this.names.length; alert(newname); }.bind(this)); }
it works jquery's $.proxy
, in one, call bind
method of function.
it isn't supported on browsers, there javascript implementation of function.prototype.bind on mdc. can use it.
this
in confusing keyword, , if want learn more this
, @ this.
Comments
Post a Comment