JS: Add Method to Prototype
This page shows you how to add method to prototype objects.
Add Method to String Prototype
Example of adding a method to 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 Prototype
Example of adding a method to Array.prototype
// add a method to array prototype // remove first and last item of a array, return the removed items as array Array.prototype.shiftAndPop = function () { return [this.shift(), this.pop()]; }; // ssss--------------------------------------------------- // test const xx = [0, 1, 2, 3, 4]; console.log( JSON.stringify(xx.shiftAndPop()) === "[0,4]", ); console.log( JSON.stringify(xx) === "[1,2,3]", );
Add Method to Number Prototype
Example of adding a method to Number.prototype
// add a method to the number prototype Number.prototype.plusN = function (n) { return (this + n); }; // test console.log(3["plusN"](4) === 7);
π‘ TIP: Do Not Add to Object Prototype
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γ
JavaScript, Object and Inheritance
- JS: Object Tutorial
- JS: Object Overview
- JS: Object Type
- JS: Test is Object Type π
- JS: Determine Type of Object
- JS: Prototype and Inheritance
- JS: Prototype Chain
- JS: Object.prototype.isPrototypeOf
- JS: Get Set Prototype
- JS: Show Prototype Chain π
- JS: Create Object
- JS: Object Literal Expression
- JS: Create Object with Parent X
- JS: Prevent Adding Property
- JS: Deep Copy Object or Array π
- JS: Test Object Equality π
- JS: Add Method to Prototype
- JS: Object Object
- JS: Object Constructor
- JS: Object.prototype