Prev Demo
Adding A Method To An Object In Javascript
Next Demo
Write code here
J
|
B
|
A
<!DOCTYPE html> <html> <head> <title>Demo</title> </head> <body> <h1>Adding method to an Object</h1> <p id="myId"></p> <script> function person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; } var myFriend = new person("Charitha", "Reddy", 23, "blue"); var myColleague = new person("Surendra", "Goud", 23, "brown"); myFriend.name = function () { return this.firstName + " " + this.lastName; }; document.getElementById("myId").innerHTML = "My friend is " + myFriend.name(); </script> </body> </html>
Note: We DO NOT save your trial code in our database.
Output