var m...">

How to store a statement in a variable using javascript

I want to save the + operator in a variable.

<head> <script type="text/javascript"> var m= function(a,b){ return ab } var jj= 10 m 10; alert(jj) </script> </head> 
+4
source share
3 answers

Avoid using eval , I would recommend using a function map:

 var operators = { '+': function(a, b){ return a+b}, '-': function(a, b){ return ab} } 

Then you can use

 var key = '+'; var c = operators[key](3, 5); 

Note that you can also save operators[key] in a variable.

+11
source

You cannot store a statement in JavaScript as you requested. You can save the function in a variable and use it instead.

 var plus = function(a, b) { return a + b; } 

Sorry, but JavaScript does not allow this operator overload.

0
source

You can not.

There are ways to use javascript to implement custom versions of operators by playing on available hooks, but there is no way to include m in + .

@dystroy has a great example of using the available hooks to implement a custom version of statements, but note that this is still just a classic example of using an object to access functions that do some work.

0
source

All Articles