JavaScript String prototype Property
Last Updated :
30 Jun, 2020
The prototype property allows to add new properties and methods to the existing JavaScript object types. There are two examples to describe the JavaScript String prototype property.
Syntax:
object.prototype.name = value
Return Value: It returns a reference to the String.prototype object.
Example 1: This example adds a property salary to the all objects.
<!DOCTYPE HTML>
< html >
< head >
< title >
JavaScript String prototype Property
</ title >
</ head >
< body style = "text-align:center;" >
< h1 >GeeksForGeeks</ h1 >
< p id = "GFG_UP" ></ p >
< button onclick = "GFG_Fun();" >
Click Here
</ button >
< p id = "GFG_DOWN" ></ p >
< script >
var up = document.getElementById('GFG_UP');
var down = document.getElementById('GFG_DOWN');
function person(name, age) {
this.name = name;
this.age = age;
}
var p1 = new person("p1", 24);
up.innerHTML = "Click on the button to add "
+ "a new property to all objects of"
+ " a given type.< br > "
+ JSON.stringify(p1);
function GFG_Fun() {
person.prototype.salary = 1000;
down.innerHTML = p1.salary;
}
</ script >
</ body >
</ html >
|
Output:
Example 2: This example adds a method info to the all objects.
<!DOCTYPE HTML>
< html >
< head >
< title >
JavaScript String prototype Property
</ title >
</ head >
< body style = "text-align:center;" >
< h1 >GeeksForGeeks</ h1 >
< p id = "GFG_UP" ></ p >
< button onclick = "GFG_Fun();" >
Click Here
</ button >
< p id = "GFG_DOWN" ></ p >
< script >
var up = document.getElementById('GFG_UP');
var down = document.getElementById('GFG_DOWN');
function person(name, age) {
this.name = name;
this.age = age;
}
var p1 = new person("p1", 22);
up.innerHTML = "Click on the button to add"
+ " a new property to all objects "
+ "of a given type.< br > "
+ JSON.stringify(p1);
function getData(name, age) {
return "Information of person < br >Name - '"
+ name + "'< br >Age - " + age;
}
function GFG_Fun() {
person.prototype.info
= getData(p1.name, p1.age);
down.innerHTML = p1.info;
}
</ script >
</ body >
</ html >
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...