Object methods

In this chapter you will learn:

  1. Add methods to objects
  2. How to add a method to a object after creating that object

Using Functions as Methods

You can add functions to an object.

<!DOCTYPE HTML><!--  j  a  v a  2 s .  c  om-->
<html>
<body>
  <script type="text/javascript">
    var myData = {
      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

Add methods after object creation

We can add new methods to an object by setting the value of a property to be a function.

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

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. How to access properties
  2. How use variable as the property name
  3. How to reference property name with space
  4. How to delete a property or method from an object
  5. How to determine if an object has a property
  6. How to enumerate object's properties
  7. How to pass in value with Object literals
Home » Javascript Tutorial » Object
Object Type
Object methods
Object properties
Object Compare