JS: Add Method to Prototype

By Xah Lee. Date: . Last updated: .

This page shows you how to add method to prototype objects.

Add Method to String

Example of adding a method to String.prototype.

[see JS: 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 JS: 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 JS: 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 JS: Prototype and Inheritance]

Object and Inheritance Topic

  1. JS: Object Overview
  2. JS: Object Type
  3. JS: Determine Type of Object
  4. JS: Object Literal Expression
  5. JS: Prototype and Inheritance
  6. JS: Create Object
  7. JS: Create Object with Parent X
  8. JS: Get/Set Prototype
  9. JS: Prevent Adding Property
  10. JS: Clone, Deep Copy Object/Array
  11. JS: Test Equality of Objects
  12. JS: Object Object
  13. JS: Object.prototype

JS Constructor/Class

  1. “this” Binding
  2. What's Constructor?
  3. Property Key "prototype"
  4. Operator “new”
  5. “instanceof” Operator
  6. Property Key “constructor”
  7. Class
  8. Keyword “extends”
  9. Keyword “super”
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS Basics
  4. JS in Depth
  5. JS Reference
  6. DOM
  7. SVG
  8. JS Misc
  9. Web Dev Blog