Thursday, April 18, 2013

Javascript: Methods

my brother's science project

Methods are an important part of OOP (object oriented programming). Remember last time we worked with properties? Whereas properties are similar to variables, a method is like a function associated with an object. Methods are important because they serve several purposes including:

1. The ability to change object property values
2. The ability to make calculations based on object properties. Functions can only use parameters as an input, but methods can make calculations with object properties. Cool, huh? 

Here's an example: 

// make cutedork here, and first give her an age of 8
var cutedork = new Object();
cutedork.age = 8; 
cutedork.setAge = setAge; 

// here, update cutedork's age to 18 using the method
cutedork.setAge(18);

Another slightly more challenging example: 

var square = new Object();
square.sideLength = 6;
square.calcPerimeter = function() {
  return this.sideLength * 4;
};

// help us define an area method here
square.calcArea = function() {
  return this.sideLength * this.sideLength
};

var p = square.calcPerimeter();
var a = square.calcArea();

No comments:

Post a Comment