Search code examples
javascriptprototype-programming

Performing math on JavaScript objects


Is there a way to overwrite the behavior of math operators like +-*/ in JavaScript?

Lets say for example I have a person object:

var Person = (function() {
  function _Person(age) {
    this.age = age;
  }
  /* I was hoping something like this would work
  _Person.prototype.add = function(input) {
    return this.age + input.age;
  };*/
  return _Person;
})();

and I make two people and want to add them together to get their total age:

var p1 = new Person(24);
var p2 = new Person(25);
var totalAge = p1+p2;//should equal 49

I've like to be able to implement a prototype method or something to specify what to do when two objects are added together. Other languages have this, for example python has __add__, does javascript have a way of doing this?

Here is the sample code in jsfiddle: http://jsfiddle.net/HYrPM/


Solution

  • JavaScript has no operator overload feature.