Add methods to objects in JavaScript

Description

The following code shows how to add methods to objects.

Example


<!DOCTYPE HTML>
<html>
<body>
<script type="text/javascript">
var myData = {<!--from  ww  w  .j  ava  2  s. co m-->
name : "JavaScript",
weather : "Good",
printMessages : function() {
document.writeln("Hello " + this.name + ". ");
document.writeln("Today is " + this.weather + ".");
}
};
myData.printMessages();
</script>
</body>
</html>

Click to view the demo

The code above generates the following result.

Add methods to objects in JavaScript