xenophobia Posted May 10, 2007 Share Posted May 10, 2007 function MyClass(){ this.filename = "Hello World"; this.myfunc = function(){ var my = function(){ alert(this.filename); } my(); } } So this is the class. Then I create an object of this class: o = new MyClass(); o.myfunc(); Will alert undefined. The problem is the variable scope. It cant get the 'filename' within the class. This will work: this.myfunc = function(){ alert(this.filename); } It can't access the second level of in the function. Any helps? Link to comment https://forums.phpfreaks.com/topic/50758-javascript-class/ Share on other sites More sharing options...
fenway Posted May 10, 2007 Share Posted May 10, 2007 Because "this" changes every time... pass it explicitly if you want to. Link to comment https://forums.phpfreaks.com/topic/50758-javascript-class/#findComment-249807 Share on other sites More sharing options...
obsidian Posted May 10, 2007 Share Posted May 10, 2007 My question is why are you over complicating the function declaration? You could simply do this: function MyClass(){ this.filename = "Hello World"; this.myfunc = function(){ alert(this.filename); } } Link to comment https://forums.phpfreaks.com/topic/50758-javascript-class/#findComment-249831 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.