Why do people write js like this? [duplicate] - javascript

This question already has answers here:
Why does any JavaScript code want to "cut the binding"?
(1 answer)
JavaScript syntax (0, fn)(args)
(2 answers)
Closed 2 years ago.
var type = (0, _reactIs.isMemo)(nodeOrComponent) ? nodeOrComponent.type.type : nodeOrComponent.type;
(0, _reactIs.isMemo) really confuse me. What's the meaning of this?
ps: I know (0, _reactIs.isMemo) this expression's value is _reactIs.isMemo

The comma operator there ensures that what's inside the parentheses is evaluated as an expression without a calling context.
To take a shorter example, if the code was:
var type = obj.fn(someArg);
then fn would be called with a calling context of obj. But the original untranspiled code, whatever it is, does not have such a calling context, so in order to be faithful to the original code, the calling context has to be removed, which can be done with the comma operator:
var type = (0, obj.fn)(someArg);
Another way of doing the same thing would be:
var fn = obj.fn;
var type = fn(someArg);
(but that takes more characters, so minifiers prefer the comma operator version)
This is a silly-looking minification trick that's often seen with imported modules. Usually, you'd only be looking at the source code, which won't have this sillyness.

Related

How do JavaScript runtimes implement binding functions to objects? [duplicate]

This question already has answers here:
Why parenthesis are ignored in the expression (o.method)()
(2 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 25 days ago.
I'm implementing a JavaScript interpreter, and I can't figure out the details of binding functions to objects in JavaScript.
A rudimentary example:
const o = {
x: 1,
getX: function() {
return this.x;
}
};
o.getX(); // returns 1
The tricky part is what happens when you assign getX to a variable:
let gX = o.getX;
gX(); // returns undefined
My question is: how does the runtime know that o.getX() gets bound to o, but gX() should be unbound? I would assume gX and o.getX are pointing to the exact same function!
I first thought that maybe the presence of the . is what makes the difference. So, in the grammar, there's a production like <method-call> ::= <expr> '.' ID '(' <expr>* ')', and this expression is treated differently (the result of evaluating the first <expr> is bound to the function found under ID) than a "regular" call (without a .).
But the following expression seems to disprove this theory, because (o.getX)() also returns 1. However, in some magical way, (gX = o.getX)() returns undefined, even though it's clear to me the assignment expression returns its right-hand size, so o.getX in this case!
Is there a simple explanation of how these semantics are implemented? I can't figure out a way that my runtime is supposed to differentiate that o.getX is bound to o, but gX, even though it's pointing at o.getX, is not bound.

Dynamically call function in javascript [duplicate]

This question already has answers here:
Calling function inside object using bracket notation
(2 answers)
Closed 6 years ago.
I rather have a seemingly trivial issue, but am not able to figure out an efficient approach.
I have a list of about 50 functions to be called such as :
globalClient.funcA(...)
globalClient.funcB(...)
globalClient.funcC(...)
My code should ideally dynamically create the name of the function (funcA / funcB/ funcC and then proceed to actually call that function. My approach below does not work (please note that these aren't exactly the actual names of the functions. I'm only giving these arbitrary names for simplicity of understanding):
var functionName = 'func'.concat('A');
globalClient.functionName
The second line is where it errors out. Now JS thinks that functionName itself is the name of the function. What I want it to do is resolve functionName to funcA and then call globalClient.funcA(...) instead.
I've thought about implementing a switch / case for this but I'm sure there is a far simpler appraoch. Any ideas?
You could use the bracket notation as property accessor.
globalClient[functionName]()
You can use the [ ] operator for accessing the properties.
var globalClient = {
funcA: function(){
console.log('funcA is called');
}
}
var functionName = 'func'.concat('A');
globalClient[functionName]();

What is the meaning of using a comma expression in a method call, such as `var proc = (0, _postcss2.default)();` [duplicate]

This question already has answers here:
Indirect function call in JavaScript
(3 answers)
Why does babel rewrite imported function call to (0, fn)(...)?
(3 answers)
Closed 6 years ago.
Looking at cssnano source code, I came across this line
var proc = (0, _postcss2.default)();
From what I've tested, it seems to do the same thing as
var proc = _postcss2.default();
Why did cssnano assign proc using the first syntax?
There is a subtle difference, in that the this value is different in default based on the two different calls. Consider the following code:
var _postcss2 = {
default: function() {
return this;
}
};
var proc = (0, _postcss2.default)();
console.log(proc); // proc === window (or undefined in strict mode)
var proc = _postcss2.default();
console.log(proc); // proc === _postcss2
_postcss2.default() calls default as a method of the _postcss2 object and sets this accordingly, but (0, _postcss2.default)(); does not, and this would be window in non-strict-mode, and undefined in strict-mode.
The way the comma operator works, is that all the expressions are executed, but only the final expression is returned, so 0, is a short meaningless expression to use the comma operator to get the function reference itself, without setting it to a variable first.
If that makes a difference in this particular case, I cannot say without looking at the code itself.
The corresponding line from the source code for this code is, let proc = postcss();, with postcss being an ES6 import. This particular code is being generated by an ES6 transpiler, probably Babel.

do I need eval? [duplicate]

This question already has answers here:
Why does eval() exist?
(6 answers)
Closed 9 years ago.
I've searched the web for what eval does and here is what I have found:
The eval() method evaluates JavaScript code represented as a string.
And I've read this question, which says that it is evil.
But I really don't understand what does it do, i.e I don't see when to use eval.
I mean:
var x= 3;
var y =5;
var z = eval("x+y");
// is the same as:
var z = x+y;
so as I see it's just adding characters to my code. Can somebody give me an example of why eval was created in the first place?
It allows execute dynamicly generated code, not just "x+y".
Eval allows you to evaluate a string as javascript code. This means you can do things like evaluate a string to call a function:
function add(x,y){
return (x+y);
}
stringToEval = 'add(5,6)';
eval(stringToEval);
This code would run the function by evaluating the string as a function call.
So I would say you do not need to use eval here. Just add the two variables.

There is any different between new F and new F()? [duplicate]

This question already has answers here:
Can we omit parentheses when creating an object using the "new" operator?
(6 answers)
Closed 5 years ago.
Think about the silution
function F(){}; //This is a Constructor function
Who can tell me there is any different between
var myInstance = new F;
and
var myInstance = new F();
? The new keyword execute followed Function immediately anyway whatever that is following by partheses ?
There is no difference. From the Mozilla Docs:
new constructor[([arguments])]
The parentheses are in square brackets, that means they are optional.
There is no practical difference, omitting the paranthesis can be done if no arguments are passed to simplify the grammar.
Note that some validators such as JSLint will report a warning if you leave them out though, as it is considered more consistent to always use the same syntax for invoking constructor functions regardless of arguments.
This similar example would be very bad if you get into this lazy habit:
var one = myFunc;
var two = myFunc();
These are two different variables, one is a function reference and the other is the return value of the function.

Categories

Resources