JavaScript:增量方法

时间:2018-03-07 22:28:36

标签: javascript oop constructor this increment

我正在尝试制作increment方法。这个看似简单的任务让我很难过。 我想要的一个例子:

var x=5; 
x.increment(); 
console.log(x); //6

我试图做的事情:

Number.prototype.increment=function(){
    this++; //gave me a parser error
};

2 个答案:

答案 0 :(得分:1)

数字在javascript中是不可变的。当您执行console.log(this)时,您会看到它将指向 Number ,其原始值为5(在我们的示例中),因此您无法更改其值。

你可以做的是从增量返回增量值(通过这样做+ 1)并将其分配给x,如x = x.increment();



Number.prototype.increment = function(){
    return this + 1;
}

var x = 5;

x=x.increment();
console.log(x);




答案 1 :(得分:0)

this无法直接更改。试试这种方式

Number.prototype.increment = function(){
    return this + 1;
}

var x = 5;

x = x.increment(); // x will be 6 here

希望这有帮助。