In python there are what's called data models also known as "underscore methods". In a class these methods allow you to specify the behaviour of your object. For instance you may define the __init__()
method which is essentially the constructor method. Or maybe the __add__()
method which defines what operations to do when the +
sign is called between two object from that class.
Here's an example code in Python
class Polynomial:
def __init__(self, *coeffs):
self.coeffs= coeffs
def __add__(self, other):
return Polynomial(*(x+y for x, y in zip(self.coeffs, other.coeffs)))
So the above __add__()
method defines the add
operation between two Polynomial objects. In this case it just adds the coefficients of same degree.
My question is: can this be done in Javascript? Can I define what happens when I do
polynomial1 = new Polynomial(1,2,3)
polynomial2 = new Polynomial(2,3,4)
polynomial1 + polynomial2
Currently, when writing polynomial1 + polynomial2
in the console, the console returns "[object Object][object Object]"