I am learning javascript. Have two blocks of code in below. As you can see that first one works just fine but second one does not. Different between them is that I use this.count to access the count variable defined in the counter2,
function counter1(start){
var count = start;
var increase = function(){
count++;
};
var getValue = function(){
return count;
};
return {
inc : increase,
get :getValue }
}
var c1 = new counter1(5);
c1.inc(); //is able to increase 1
console.log(c1.ge());//can return 6
function counter2(start){
var count = start;
var increase = function(){
this.count++;
};
var getValue = function(){
return this.count;
};
return {
inc : increase ,
get :getValue }
}
var c2 = new counter2(5);
c2.inc(); //can NOT access this.count
console.log(c2.ge());//return NaN
I am a little confused with the "this" in counter2 as you can see, when I debug the code, "this" is counter2, but just has no access the the count variable
So could you help me to understand why 'this' in counter2 is not have the access to the count variable? and why I can access count variable in the increase function in counter1 even if I did not use "this". Does this makes the code "worse" (less accessible)?
Thanks