0

In python:

a + b

means

a.__add__(b)

which means there are operator methods which actually execute the operations on behalf of the operator sign.

Is there anything similar in Javascript? or any info about the mechanics of an aritmetic operation? I am not looking for solutions using functions like:

function add(a, b) {...}

I think it has to do with the properties of the numbers and corresponding variables.

3
  • afaik no, you cannot redefine what '+' means. There are a few ways to redefine how iteration occurs over an object (with symbol.iterator), so you can conceivably decide what for (x of y) means, but not + or most other things like it. Commented Mar 19, 2018 at 10:58
  • 1
    No, there is no equivalent. This would be more answerable if you gave an example of what you're trying to accomplish. Generally though, Javascript operators aren't overloadable directly or indirectly. Commented Mar 19, 2018 at 10:58
  • I am not trying to modify them. Say I am writing a vector class and I need to add two vectors. In python, I can use this functionality so that when I write v3 = v1 + v2, they are added. I do not need anything like v3 = v1.add(v2). I want to do the same thing with JS. Commented Mar 19, 2018 at 11:09

1 Answer 1

1

There's this babel transform which might be useful for you.

https://www.npmjs.com/package/babel-plugin-operator-overload

It's not very popular or very used, I personally would avoid it.

Apart from that, no, that doesn't happen in JS. You just use the methods on the objects.

Sign up to request clarification or add additional context in comments.

5 Comments

I think the second example, the Point Add, looks like what I want. I need to work on that.
Sure, though again I'd recommend you instead think of how you can write a function that does that, rather than overloading +.
I do not know where to break in (when the parser(?) catches a + sign) and how to handle it. That is why I was asking for info on the mechanics. What happens when the + sign is deteceted? For the plugin, it says its range is limitted to your function definition; so I understand + (and the others) wil be overloaded during vector operations only.
@user2800464 + is only designed to work on numbers or strings, and there are specifications how it will coerce/interpret its arguments into one of those two things and then add or concatenate them. You cannot further overload its meaning in regular Javascript.
Babel takes what you've written and changes it to work in javascript. Babel compiles what you've written into valid javascript -- overloading is not valid javascript. The babel compiler (or transpiler I guess), when it detects a '+' in a context where you've defined an overload, changes that section of code to use your overload code instead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.