Anupama H

``````var p1 = new Point(4, 12);
var p2 = new Point(2, 4);

var subResult = new Point();
subResult.value = p1 - p2;

console.log("Subtraction : " + subResult.value); // "Subtraction : Point(2, 8)"

var mulResult = new Point();
mulResult.value = p1 * p2;

console.log("Multiplication : " + mulResult.value); // "Multiplication : Point(8, 48)"

var divideResult = new Point();
divideResult.value = p1 / p2;

console.log("Division : " + divideResult.value); // "Division : Point(2, 3)"``````

Tricks

1. "+", "-", "*", "/" operators call operand.valueOf() function for object type operands

2. Define setter function on value property of Point Prototype

``````function Point(x, y) {
this.x = x;
this.y = y;
Point.operands = [];
};``````
``````Point.prototype.valueOf = function() {
/*
smallest number for which + , - , * , /
operations give different values
*/
Point.operands.push(this);
return 3;
}``````

``````Point.prototype.toString = function (x, y) {
return "Point(" + this.x + ", " + this.y + ")";
};``````

p1 + p2

p1.valueOf() + p2.valueOf()

```var p1 = new Point(4, 12);
var p2 = new Point(2, 4);
var p3 = new Point();

p3.value = p1 + p2;
```

6

6

Point.operands = [p1, p2]

``````Object.defineProperty(Point.prototype, "value", {
set: function(value) {
var l = Point.operands[0];
var r = Point.operands[1];
switch(value) {
case 6:
/* 3 + 3 = addition */
this.x = l.x + r.x;
this.y = l.y + r.y;
return this;
case 0:
/* 3 - 3 = subtraction */
this.x = l.x - r.x;
this.y = l.y - r.y;
return this;
case 9:
/* 3 * 3 = multiplication */
this.x = l.x * r.x;
this.y = l.y * r.y;
return this;
case 1:
/* 3 / 3 = division */
this.x = l.x / r.x;
this.y = l.y / r.y;
return this;
}
},
get: function() {
return this.toString();
}
});``````