Objects and Methods in JavaScript
Monday, Feb 3, 2020
JavaScript
JavaScript
In a previous note, constructors were introduced as blueprints for creating objects. In addition to defining the state of objects, constructors can also define the behavior of objects through methods. Methods are functions but defined uniquely for a particular type of objects. This is the fundamental notion of object-oriented programming.
In the example below, I show this feature by creating a constructor called
point (in 2d cartesian coordinates). Point's state is defined by two
attributes - x and y. Following this, two methods are defined for point - it's
distance from the origin through mag
method and it's distance from another
point through dist
method:
Point and it's Methods
// describing methods for objects
function Point(x, y) // point in 2d coordinates
{
this.x = x;
this.y = y;
this.mag = function() // distance from origin
{
return Math.sqrt(this.x*this.x + this.y*this.y).toFixed(2)
}
this.dist = function(other) // distance from another point
{
x_sq = Math.pow((this.x - other.x), 2);
y_sq = Math.pow((this.y - other.y), 2);
return Math.sqrt(x_sq + y_sq).toFixed(2)
}
}
Let's test it
p1 = new Point(2, 3);
console.log(p1.mag());
p2 = new Point(3, 4);
console.log(p1.dist(p2));
3.61
1.41