繁体   English   中英

方法调用模式

[英]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预期的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM