object method

Description

object methods are functions which define the action on your object.

Example

The following code defines a method to display object's properties.


var myData = {
  name : "JavaScript",
  weather : "Good",
  printMessages : function() {//  w  ww  .  j  a  v  a  2 s.co m
    console.log("Hello " + this.name + ". ");
    console.log("Today is " + this.weather + ".");
  }
};
myData.printMessages();

The code above generates the following result.

Example 2

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


var myData = {
  name : "JavaScript",
  weather : "Good",
};//from w w  w .j ava  2s  .  c o  m
myData.sayHello = function() {
  console.log(this.name);
};
    
myData.sayHello();

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions