Ben Rivers
Ben Rivers

Reputation: 139

JavaScript: Increment Method

I'm trying to make an increment method. This seemingly easy task has stumped me. An example of what I want:

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

What I tried to do:

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

Upvotes: 1

Views: 1002

Answers (2)

yajiv
yajiv

Reputation: 2941

Numbers are immutable in javascript. when you do console.log(this) you will see it will point to Number whose primitive value is 5(in our case), so you can not change it's value.

What you can do is return incremental value(by doing this + 1) from incremnt and assign it to x like x=x.increment();

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

var x = 5;

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

Upvotes: 1

Ashok Vishwakarma
Ashok Vishwakarma

Reputation: 689

this cannot be changed directly. Try this way

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

var x = 5;

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

Hope this helps.

Upvotes: 0

Related Questions