Is it possible to change the functionality of predefined methods in javascript?

We can achieve this using Prototype.

What is Prototype?

Every JavaScript function has a prototype property (this property is empty by default) and you can attach properties and methods on this prototype property. When you want to implement inheritance prototype is enumerable. An object prototype points to the object parent where it inherited its property from.

Prototype basically used for two things:-

  1. Prototype-based inheritance: All inheritance in JavaScript is possible through the prototype property.
  2. Accessing properties of objects: Prototype is also important for accessing properties and methods of an object. If you want to access a property of an object the search for the property begins directly on the object. If it can’t find the property there then it looks for the property on the object's prototype (the object it inherited it properties from). If still property is not found then search moves to the prototype of the object prototype (parent of the parent). This is called prototype chain. It will go on until it finds null).

How to change the functionality of predefined methods?

To do this we need to overwrite the method in its prototype. Once the method is overwritten you can't get back the original functionality.

var test = "abcd";

console.log("Before modication -- " + test.toUpperCase()); 

//changing the default behaviour
String.prototype.toUpperCase = function()return 'function modified';
}

console.log("After Modification -- " + test.toUpperCase());
console.log("After Modification -- " + "sdafdf".toUpperCase());

In the above example, I changed the return of toUpperCase() method. By default, this method will convert the given string to uppercase and returns the same. But now I changed the function to return a string "function modified". So wherever you call the toUppercase() method will return "function modified"

Working example: https://jsfiddle.net/shanmu20/u49n93sf/

To view or add a comment, sign in

More articles by Shanmuganathan B

Explore content categories