I tried using "this" inside the function, but "this" is somehow the entire Window and not as i was expecting, the value of var1.
The reason
this isn't acting the way you expect it to is because you're using an arrow function. Arrow functions do not bind their own
this, and instead inherit the one from the parent function. If you want
this to refer to the specific Number object, you will need to define the function using the
function keyword instead of defining it as an arrow function.
Though that function has even worse issues to worry about, since you're also not actually doing any adding in the function, and you're also trying to use
min and
max parameters without supplying any
min and
max arguments.
The correct way to write/use that function would be something like this:
JavaScript:
Number.prototype.add = function(value, min, max) {
let result = this + value;
if (min !== undefined) {
result = Math.max(result, min);
}
if (max !== undefined) {
result = Math.min(result, max);
}
return result;
};
// Usage examples:
let butt = 40;
butt = butt.add(9000, 0, 99); // 99
butt = butt.add(-9000, 0, 99); // 0
butt = butt.add(9000); // 9000
Though I'm just telling you that for academic purposes. In this particular situation, you probably should do what
@Mac15001900 is advising.