I’m very new to Javascript and somewhere i found this code
var myObject = {
value: 0,
increment: function (inc) {
this.value += typeof inc === 'number' ? inc : 1;
}
};
In the above object the increment function is acessing the value variable using this. But in languages like java, the public method can access the private member without this also.. why it is not possible here?
Every JS function has a reference to a chain of scopes, in which it tries to lookup the variables. This chain is as follow:
The current object (and its fields) is not in the chain, so you have to reference it with
this.