1

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?

0

4 Answers 4

1

Because value is trying to get a variable named value in the global scope, and here you are in an object and this is a property of the object.

Sign up to request clarification or add additional context in comments.

Comments

0

Every JS function has a reference to a chain of scopes, in which it tries to lookup the variables. This chain is as follow:

  • local variables of current function
  • local variables of function that called it
  • (...)
  • global variables

The current object (and its fields) is not in the chain, so you have to reference it with this.

1 Comment

Do u mean scope is the problem? fucntions are in different scope?
0

Because this is Javascript, and not Java. There is no relation or similarity between the two languages, even though Javascript has "Java" in its name.

Comments

0

It's because of your scope... you could try it like this:

var myObject = (function(){
    var value = 0,
        increment = function (inc) {
            value += typeof inc === 'number' ? inc : 1;
            return value;
        };
    return {increment:increment}
})();
console.log(myObject.increment());
console.log(myObject.increment());
console.log(myObject.increment());

2 Comments

You did not understand the question!
Yes - the code is working - he is asking why he needs the this part

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.