JavaScript: Add Method to Prototype
This page shows you how to add method to prototype objects.
Add Method to String
Example of adding a method to String.prototype
.
[see String.prototype]
// add a removeVowels method for string prototype String.prototype.removeVowels = function () { return this.replace(/[aeiou]/g, ""); }; // example call console.log("how are you".removeVowels()); // "hw r y"
Add Method to Array
Example of adding a method to Array.prototype
.
[see Array.prototype]
// add a method to array prototype // remove first and last item of a array, return the removed items Array.prototype.shiftAndPop = function (){ return [this.shift(), this.pop()]; }; // test let aa = [0,1,2,3,4]; console.log(aa.shiftAndPop()); // [0,4] console.log(aa); // [1,2,3]
Add Method to Number
Example of adding a method to Number.prototype
.
[see Number.prototype]
// add a method to the number prototype Number.prototype.plusN = function (n) { return (this + n); }; // test console.log( 3["plusN"](4) ); // 7
Do Not Add to Prototype Object
Note: Adding a method to prototype is not a recommended practice. Because, adding to global object changes the language unexpectedly and create conflicts if other people also do it.
[see Prototype and Inheritance]