Search code examples
javascriptmethodsinvocation

Method invocation pattern


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


myObject.increment( );
document.writeln(myObject.value); //1

myObject.increment(2);
document.writeln(myObject.value); //3

I can understand this function.

But I have trouble to understand why result of second call is 3? Because in my mind that result should be 2.

In my head process is looking like this:

var myObject = {
    value:0,
    increment: function(2){
        0 += 2;}
};

And result in my opinion should be 2, but what is reason to be 3 instand.


Solution

  • Please think it as single json

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

    Then you called

    myObject.increment( );
     document.writeln(myObject.value); //1
    

    Which updated object as

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

    Now you call this

    myObject.increment(2);
    document.writeln(myObject.value); //3
    

    so now it will 3 as expected