1

I want to overwrite this in Number prototype function and dynamically change the value of variable, for example:

Number.prototype.xd = function(){
  this = 11212;
}
var a = 171717;
console.log(a);
a.xd();
console.log(a);

is what I want, but it throws an error. In this way works Array.prototype.pop method:

fruits = ["a","b","c","d"];
console.log(fruits);
fruits.pop();
console.log(fruits);

Can I do the same?

3 Answers3

6

You cannot achieve what you want because numbers in JS are immutable.

Another reason why this wouldn't work is because this is already dynamic in JS by its definition so it will automatically change every time a function is called, depending on how it's called.

nem035
  • 34,790
  • 6
  • 87
  • 99
0

That's impossible. The number is one of JS primitives and as all primitives it wraps into Number in runtime.

ajile
  • 666
  • 1
  • 10
  • 18
0

You can modify complex types (object, array, function), but unfortunately you can't change primitive types (string, number, boolean, null, undefined). This property is referred to as "immutability".

You may also find this answer helpful: https://stackoverflow.com/a/16115543/3236521

Community
  • 1
  • 1
christianbundy
  • 666
  • 9
  • 21