Skip to content Skip to sidebar Skip to footer

Is There A Way To Add A Prototype To Variables (numbers), And The Prototype Can Change The Variable Itself?

I know its a bad idea to add prototypes to native javascript objects, but I'd like to add a prototype to a variable such as Number.limit(min, max); where the variable can be change

Solution 1:

No, it's not possible (for the most part) - the best you'll be able to do is to return the new value, which the caller reassigns:

Number.prototype.limit = function(min, max) {
  if (this < min) {
    return min;
  } else if (this > max) {
    return max;
  }
  return this;
};
let num = 5;
let newNum = num.limit(10, 15);

console.log(newNum);

If you're familiar with Javascript, to understand why it's not possible, it might help to look at the invocation of a method without the implementation:

let someVar = <something>;
someMethod(someVar);

No matter what someMethod does, the object or primitive that the someVar variable name is bound to in the scope above is not changeable by someMethod (unless someMethod is also defined in that scope, which is a bit weird and is often not the case). Unless someMethod also has lexical scope of someVar and does someVar = <somethingElse>, the someVar will remain referencing <something>. Although someMethod may mutate the <something>, if it's an object, it cannot reassign the someVar variable name in the other scope.


Post a Comment for "Is There A Way To Add A Prototype To Variables (numbers), And The Prototype Can Change The Variable Itself?"