Fri, 17 May 2024


How to add a prototype to a JavaScript object?

By: Anton, NetArt Media
Fri, 2 October 2020

Adding a prototype is an way to add a new property or methos to a predefined JavaScript class.
The syntax for adding a prototype is:

contructor.prototype.name = value

constructur
The name of the constructor function object you wish to change.

name
The name of the property or method you wish to create

value
The value initially assigned to the new property or method.


Let's supopse you wish to add a method called FirstChar to default String contructor which returns the first character of a string. How to do this?

First you need to define the GetFirstChar method

function GetFirstChar(x)
{

return x.substring(0,1);

}

And then, set the protype:

String.prototype.FirstChar = GetFirstChar;

so finally you may try this:


<script>

function GetFirstChar()
{

return this.toString().substring(0,1);

}

String.prototype.FirstChar = GetFirstChar;

var testString=new String("NetArt Media");

document.write(testString.FirstChar());


</script>


Category: Javascript
Share this post:



See All Scripts






Subscribe for our newsletter

Receive the latest blog posts direct in your mailbox