javascript - How can you call a variable in a method from within the object? -
i'm trying learn oop in javascript.
i made following code supposed return time spent in mailthread:
function mailthread(url) { this.timerison = true; this.c = 0; this.url = url; this.timercounter = function () { if(this.timerison) { //doesnt called?? console.log('timerison'); this.c = this.c + 1; console.log(this.c); } else { this.windowtimeopen = this.c } } this.timerinterval = setinterval(this.timercounter, 1000); } mailthread1 = new mailthread('test');
however this.timerison seems return undefined preventing timer running. doing wrong here?
also tested in following fiddle: http://jsfiddle.net/b5vt5/
the problem within scope of function called timercounter, "this" refers function itself. this:
function mailthread(url) { var self = this; self.timerison = true; self.c = 0; self.url = url; self.timercounter = function () { if (self.timerison) { //using self instead of console.log('timerison'); self.c=this.c+1; console.log(self.c); } else { self.windowtimeopen = self.c } } self.timerinterval = setinterval(self.timercounter,1000); } mailthread1 = new mailthread('test');
i recommend @ mdn introduction oop
Comments
Post a Comment