ok, this is really my first time doing my first class with javaScript, I have studied to use JQuery so much for months so its not really not hard me to teach. In this code I will be asking a lot of questions..
ok this is the code my first javascript class
window.myclass = function(){
this.n1 = 0;
this.n2 = 0;
this.ans = 0;
this.hehe = 0;
this.defaultNumbersAdd = function(){
this.hehe =setInterval(function(){
//just an example of inert function...
//the truth is i can't grab the this.n1 and this.n2...
this.ans = this.n1 + this.n2;
},100);
clearTimeout(this.hehe);
};
this.returnAns = function(){
return this.ans;
};
this.getAnswer = function(){
this.defaultNumbersAdd(); //i want to reuse this function but I can't access it
return this.returnAns(); //and also this one
};
this.modifynumbers = function(n1,n2){
this.n1 = n1;
this.n2 = n2;
};
};
var myclassins = new window.myclass();
alert(myclassins.getAnswer);
now my questions are
1) how can i grab the class variables(this.vars) to be used inside my functions
2) how can i use other functions inside of another function
NOTE: sorry if my explanation is kinda vague…
The
thispointer directly inside of your window.myclass object points to that object itself, and you’re using it to define what are essentially properties of that object, such as n1 and n2.However, from within the functions defined within your object, the
thispointer refers to the function, not the object. ***However, within setTimeouts and setIntervals, the “this” keyword refers to the window object, or the global scope. (See update at the bottom for example.)Thus, you can just simply access the properties directly, using the name of the variable at the global scope which you used to instantiate the class,
However, the above method ties your class to the name given to the object at instantiation time, and is only useful for a single object.
A better solution is to define a variable within the object and reference the “this” pointer using it:
Lastly, another technique is to define the function using a closure, passing in the “this” pointer into a function that returns another function, like so:
The least complex method, of course, is to use the
var self; however, in JavaScript there are several different ways to accomplish a task, and these techniques can prove handy in different scenarios.UPDATE:
@apsillers pointed out that the “this” keyword points to the window object when referenced inside callbacks invoked by setTimeout and setInterval functions. Here is an example:
Output of someFunct():
As you can see, inside of a setTimeout, “this” clearly points to the window, or global scope! (NOTE: You can actually take that little code snippet and run it in your Chrome or Firebug debugger.)