方法调用模式

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

我能看懂这个功能

但是我很难理解为什么第二次调用的结果是3? 因为在我看来结果应该是 2.

在我的脑海中,流程是这样的:

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

我认为结果应该是 2,但为什么要变成 3。

请当成单身json

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

然后你打电话给

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

哪个对象更新为

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

现在你称之为

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

所以现在它会像预期的那样是 3