Add method to JavaScript object

We can add a method to a JavaScript object. First, define a method and then assign that method as a property to an object.

Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<html>
<body>
<script>
function stuClassName(className){
this.className=className;
}
function Student(name,rollNo){
this.name=name;
this.rollNo=rollNo;
this.stuClassName= stuClassName;
}
var student=new Student("Jai", "MCA/07/06");
student.stuClassName("MCA Final");
document.write("Name: " +student.name + "</br>");
document.write("RollNo: " + student.rollNo + "</br>");
document.write("Class: " + student.className);
</script>
</body>
</html>
<html> <body> <script> function stuClassName(className){ this.className=className; } function Student(name,rollNo){ this.name=name; this.rollNo=rollNo; this.stuClassName= stuClassName; } var student=new Student("Jai", "MCA/07/06"); student.stuClassName("MCA Final"); document.write("Name: " +student.name + "</br>"); document.write("RollNo: " + student.rollNo + "</br>"); document.write("Class: " + student.className); </script> </body> </html>
<html>
<body>
<script>
function stuClassName(className){
this.className=className;
}
function Student(name,rollNo){
this.name=name;
this.rollNo=rollNo;
this.stuClassName= stuClassName;
}
var student=new Student("Jai", "MCA/07/06");
student.stuClassName("MCA Final");
document.write("Name: " +student.name + "</br>");
document.write("RollNo: " + student.rollNo + "</br>");
document.write("Class: " + student.className);
</script>
</body>
</html>