Add methods to an object after object being created in JavaScript

Description

The following code shows how to add methods to an object after object being created.

Example


<!DOCTYPE HTML>
<html>
<body>
<script type="text/javascript">
var myData = {<!--   w  w  w  . j a  va  2  s.c om-->
name : "JavaScript",
weather : "Good",
};
myData.sayHello = function() {
document.writeln(this.name);
};

myData.sayHello();
</script>
</body>
</html>

Click to view the demo

The code above generates the following result.

Add methods to an object after object being created in JavaScript