In this article, the task is to add a method to the String class in JavaScript. There are two approaches that are described with the proper examples:
Approaches to add Methods to String Class:
- using Object.defineProperty() method
- using String.prototype.propertyName method
Approach 1: Using Object.defineProperty() method
The Object.defineProperty() method is used to define a new property directly to an object or modify an existing property. It takes 3 arguments, the first is Object, the Second is propertyName, and the last is propertyDescription. In this example, the sum of the length of strings is returned.
Syntax:
Object.defineProperties(obj, props)
Example: This example uses the above-explained approach.
Javascript
// Input string let str1 = "neveropen" ; let str2 = "A Computer Science Portal" ; // Display input string console.log(str1); console.log(str2); // Define custom method Object.defineProperty(String.prototype, "SumOfLength" , { value: function (param) { return this .length + param.length; }, }); // Run custom method function GFG_Fun() { // Apply custom method let res = str1.SumOfLength(str2); // Display output console.log( "Total length: " + res); } // Funcion call GFG_Fun(); |
neveropen A Computer Science Portal Total length: 38
Approach 2: Using String.prototype.propertyName method
The String.prototype.propertyName is used to add a new method to the String class. Define a method that takes arguments passed by the object and performs the desired operation. In this example, the sum of the length of strings is returned.
Syntax:
object.prototype.name = value
Example: This example uses the above-explained approach.
Javascript
// Input string let str1 = "JavaScript" ; let str2 = "A Scripting Language for Web" ; // Display input string console.log(str1); console.log(str2); // Define custom method String.prototype.SumOfLength = function (arg) { return this .length + arg.length; }; // Run custom method function GFG_Fun() { // Apply custom method let res = str1.SumOfLength(str2); // Display output console.log( "Total length: " + res); } // Funcion call GFG_Fun(); |
JavaScript A Scripting Language for Web Total length: 38