JavaScript Methods
//Here is an object... var meter = new Object(); meter.time = 0; //Here we define a method,one that adds "time" to the meter object... meter.addTime = function (time){ meter.time = time; }; //Calling the method... meter.addTime(40);Methods can also do calculations against object properties...
//The object... var meter = new Object(); meter.time = 15; //Here we define a method,one that adds "time" to the meter object... meter.addTime = function (time){ meter.time = time; }; //Here the method adds the existing meter time to the new input... meter.addMoreTime = function (MoreTime) { return MoreTime + meter.time; }; //Calling the method.. meter.addMoreTime(25);View a running example of the code above.
Methods can also be used for more than one object, using the "this" keyword. You use the "this" keyword to stand in for the name of the specific object that this method will operate on, when it is called...
//Here is a method to add time to any one of a number of meter objects, //defined below. The method needs to go above the objects it is being //used by... var addTime = function (time){ this.time = time; }; // now we make a meter object var meter1 = new Object(); meter1.time = 0; meter1.addTime = addTime; // And we make a second meter object var meter2 = new Object(); meter2.time = 0; meter2.addTime = addTime; // Then we call the method, in order to add 15 minutes to Meter #2. meter2.addTime(15)Example here.