how can I access this inside a function without using that or self in javascript? -
im trying write oop in javascript, , stumbled upon problem sure im going have later on in code , wish deal now.
for illustration take code:
var feedclass = function(){ this.init = function(){ this.loaditems(); }, this.loaditems = function(){ var = this; // heres problem function inner(){ that.startloading(); } inner(); }, this.startloading = function(){ alert("started loading"); } this.init(); }; var feed = new feedclass(); the problem im going utilize lot of inner functions phone call "this", code messy if kept writing var = this within every scope. there pattern can utilize or way around it?
you can utilize call method set context function:
this.loaditems = function(){ function inner(){ this.startloading(); } inner.call(this); }, the apply method works similarly, difference how specify parameters in call.
you can utilize bind method set context of function. allows bind context function , pass function reference on called later:
this.loaditems = function(){ function inner(){ this.startloading(); } var = inner.bind(this); i(); }, note: bind method not supported in ie 8 or earlier.
javascript
No comments:
Post a Comment