This question already has answers here:
Javascript: operator overloading
(9 answers)
Closed 4 years ago.
Let's say i want an object that when multiplied with, it multiplies by two and subtracts 1.
The syntax would look like this:
var a = {
on_multiply: function(context){
return context*2-1
}
};
alert(2*a);
This would output 3.
I don't want to write
"a.on_multiply(2)"
Is there a way to do this?
If yes, is it possible to do this with arrays or matrixes also?
The simplest way I can think of to make the above example work is to assign a function named a, and have the context as a parameter of that function:
function a(context) {
return (context * 2) - 1;
}
And if you really wanted a to be a function assigned to a name:
const a = context => 2 * context - 1;
And the above in ES5 syntax:
const a = functipn(context) {
return (context * 2) - 1;
}
Hopefully this helps!
Related
This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
What is the difference between the `=` and `==` operators and what is `===`? (Single, double, and triple equals)
(5 answers)
Closed 11 months ago.
So I'm making an idle game and I want when you buy a 'carrot patch' in this example, the price of said 'carrot patch' will raise by 50%. However this doesn't happen.
Here's my code:
var patchPrice = 10;
function buyPatch() {
if (affordable = true) {
var patchPrice = patchPrice * 1.5;
}
}
you have declared the patchPrice variable twice. so it will overwrite the previous value. just remove the second var and it will work.
These were problems with js before es6 I recommend you to use es6 const and let to declare variables.
Try == in the comparison or simply omit the (== true) as it is already a boolean.
var patchPrice = 10;
function buyPatch() {
if (affordable == true) {
var patchPrice = patchPrice * 1.5;
}
}
Avoid using "VAR" unless you wanna work with function scope variables.
This question already has answers here:
Closure in JavaScript - whats wrong?
(7 answers)
"add" function that works with different combinations of chaining/arguments
(4 answers)
Puzzle: JS Function that returns itself until there are no arguments
(5 answers)
Variadic curried sum function
(19 answers)
Closed 1 year ago.
I just started learning closures in JavaScript and I'm trying to understand a basic problem.
For example, I'm trying to implement the sum method: sum(1)(4)(5)
const sum = (a) => {
return (b) => {
if(typeof b === 'number')
return sum(a+b)
return a;
}
}
When I call: console.log(sum(1)(4)(5)()) it works perfect and return 10. However, if I call console.log(sum(1)(4)(5)), it returns [Function (anonymous)]. Why?
Thanks
Every time you call your function like:
sum(1)(10)
you are returning the inner function:
(b) => {
if(typeof b === 'number')
return sum(a+b)
return a;
}
Because type of b === 'number' and you are returning sum(a+b) that calls
again the function sum and returns again the inner function. Thats why when you finally put the last parenthesis like:
sum(1)(10)()
The inner function will execute and type of b in this case is different from number and will return 'a' that already contains the sum of the values.
This question already has an answer here:
Where can I get info on the object parameter syntax for JavaScript functions?
(1 answer)
Closed 5 years ago.
const f = ({x,y})=>{...do something...};
const f = (x,y)=>{...do something...};
What is the difference between these two lines ?
My understanding is both pass "x" and "y" are arguments.
Are both the same then ?
The first one uses destructuring you can use it as
f({x: 0, y: 1})
you pass one object with fields x and y
and then in body you can access fields of object as variables x and y.
In the second one you have to pass 2 variables
f(0, 1)
Bodies can be the same of those functions and they would work analogically
for instance
=> { return x + y; }
but params should be passed in different ways
The first one you're passing an object as a parameter. But I don't think it's a working example. Here is one
class O {
x;
y;
}
const example =(o:O)=>{
//do something
return o.x+o.y;
};
The equivalent is
var example = function example(o) {
//do something
return o.x+o.y;
};
The second one you're passing two parameters the equivalent is
var example2 = function example2(x, y) {
//do something
return 0;
};
This question already has answers here:
Javascript: operator overloading
(9 answers)
Closed 5 years ago.
This is more of a "for fun" sort of thing, as it would be impractical to actually use this. I just want to satisfy my curiosity as to whether or not it's even possible.
I have a function...
function longAdd(a,b){
//computation here
return sum;
}
...which "adds" the values of a and b together as a string; meaning, it iterates through each character and adds them up. Thus, it can compute numbers which are greater than what could otherwise be achieved.
(for the purposes of this question, the actual code should not be relevant, so it is not included)
My question is: would it be possible to directly change the "+" operator to use this function? For instance,
c+d
anywhere in the code would essentially compute longAdd(c,d).
Any possible hacky ways to achieve this? For that matter, can the behavior of any operators be directly changed?
Note: Yes, I am aware this would screw up concatenation and big, numerical values would have to stay strings. This is just a concept I'm curious about.
My question is: would it be possible to directly change the "+" operator to use this function?
No, JavaScript has no user-defined operator overloading at all.
The nearest I can see getting is defining an object with its own valueOf method which returns the result of converting itself to a string and doing your longAdd just on itself, and returning that result. Then the existing + would trigger that behavior on the objects referenced by a and b.
That's not overloading +, just taking advantage of the behavior it already has:
function Thing(val) {
this.val = val;
}
Thing.prototype.valueOf = function() {
// Here I'm just doubling it; you'd actually do your longAdd thing
return this.val * 2;
};
var a = new Thing(1);
var b = new Thing(2);
console.log(a + b); // 6 (1 * 2 + 2 * 2)
Or with ES2015's class:
class Thing {
constructor(val) {
this.val = val;
}
valueOf() {
return this.val * 2;
}
}
const a = new Thing(1);
const b = new Thing(2);
console.log(a + b); // 6 (1 * 2 + 2 * 2)
Or just with objects, no constructors:
var thingPrototype = {
valueOf: function() {
return this.val * 2;
}
};
var a = Object.create(thingPrototype);
a.val = 1;
var b = Object.create(thingPrototype);
b.val = 2;
console.log(a + b); // 6 (1 * 2 + 2 * 2)
This question already has answers here:
How do I make JavaScript Object using a variable String to define the class name?
(10 answers)
Using a variable value to call an array element
(7 answers)
Closed 8 years ago.
Hard to explain.. I basicly want to do the following:
var doWhat = "speak";
var speak = {
hello: function() { alert: "Hello!"; }
};
// Won't work
doWhat.hello();
It's a bad example, but you should be able to get what I mean.
Is it possible somehow ?
You can use eval(doWhat).hello();. That way the contents of doWhat will be evaluated to the object reference.
You can do something like
var doWhat = {}, str = "speak";
doWhat[str] = {
hello : function() {}
};
doWhat[str].hello();
jsName = 'PageIndexController';
//ST1
eval("if( typeof jsName === 'undefined')alert(111);");
//ST1
eval("if( typeof " + jsName + " === 'undefined')alert(222);");
//ST1 not work
//ST2 work and the output: 222;
//there are two different way using eval, we will get 2 different outcome.