1

according to 1, When we calling the increment method. a is increasing with the given parameter to the function, if no parameter passed then it is inc by 1.

But according to 2, when i write the code like below, a is not inc, always 1 only. Why??.... Please solve this....

// 1
var Obj1 = {
    a: 0,
    increment: function(inc) {
        this.a += typeof inc === 'number' ? inc : 1;
    }
};

// 2
var Obj1 = {
    a: 0,
    increment: function(inc) {
        this.value = this.a + typeof inc === 'number' ? inc : 1;
    }
};

2 Answers 2

1

when i write the code like below, a is not inc, always 1 only. Why??

Because you are never assigning any new value to a

Make it

var Obj1 = {
   a: 0,
   increment: function (inc) {
      this.a = this.value = this.a + typeof inc === 'number' ? inc : 1;
   }
};

or

var Obj1 = {
   a: 0,
   increment: function (inc) {
      this.value = this.a + typeof inc === 'number' ? inc : 1;
      this.a = this.value;
   }
};
Sign up to request clarification or add additional context in comments.

Comments

0

i don't know why you need value but

    var Obj1 = {
     a: 0,
     increment: function (inc) {
       this.a = this.a + typeof inc === 'number' ? inc : 1;
     }
    };

Comments

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.