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

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.

Related

Why are methods not valid constructors? [duplicate]

This question already has answers here:
Constructor behaving differently using ES6 shorthand notation
(3 answers)
TypeError: function is not a constructor (evaluating 'new self.f(1)')
(1 answer)
What is the difference between these object literals?
(1 answer)
Closed 5 months ago.
Regardless of intent, it's unclear to me why one is valid and other other is not. If someone could point to the relevant part of the language spec, that would be especially helpful.
class Foo {
bar() {}
}
Foo.prototype.baz = function() {};
const f = new Foo();
new f.baz(); // Valid
new f.bar(); // invalid, throws error
As pointed out in the comments on the original question, the spec defines it this way. A constructor must have the internal [[Construct]]s, and while ordinary function expressions do get this slot set, method definitions do not. This is described in MDN (as another commenter pointed out) as well.

Why do people write js like this? [duplicate]

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.

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 does F= or F=a=> mean in Javascript? [duplicate]

This question already has answers here:
What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?
(14 answers)
Closed 8 years ago.
I've been pursuing the codegolf site lately with a focus on Javascript. I keep seeing something that I don't understand and can't find an answer to. Check out this answer. The first line starts with F=a=>. I assume that this is a shorthand function declaration, but I can't find any reference to it elsewhere on the web. Can someone explain, or point me to a good document about this syntax?
Feel free to tag this question. Hard to tag when I don't know what I'm looking at.
If you look at the ES6 definition document this is the Arrow function symbol
Looking at MDN's documentation this is just shorthand for declaring an anonymous function
An interesting difference is that the arrow function syntax provides a closure so (quoting from MDN)
In ECMAScript 3/5, this issue was fixed by assigning the value in this
to a variable that could be closed over.
function Person() {
var self = this; // Some choose `that` instead of `self`.
// Choose one and be consistent.
self.age = 0;
setInterval(function growUp() {
// The callback refers to the `self` variable of which
// the value is the expected object.
self.age++;
}, 1000);
}
Alternatively, a bound function could be created so that the proper
this value would be passed to the growUp function.
Arrow functions capture the this value of the enclosing context, so
the following code works as expected.
function Person(){
this.age = 0;
setInterval(() => {
this.age++; // |this| properly refers to the person object
}, 1000);
}
var p = new Person();
In those two examples you can see the difference very clearly
function() {
console.writeline('es5');
}
versus
() => {
console.writeline('es6');
}
Yea, that is a shorthand for a function declaration.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Why does calling a method with parenthesis, eg. (obj.func)(), still set `this`? [duplicate]

This question already has answers here:
How does JavaScript determine when to give a function call a "this" context? [duplicate]
(2 answers)
Closed 8 years ago.
What exactly is the parsing rule in JS that results in the following:
Let's say we have this function
getThis = function(){
return this;
}
These all work as expected using the "previous dot" rule:
getThis(); //=> Window
obj = {getThis: getThis};
obj.getThis(); //=> obj
getThisTwo = obj.getThis;
getThisTwo(); //=> Window
However, this surprises me:
(obj.getThis)() //=> obj ...WAT
My intuition would be that it would behave exactly like the 3rd example (getThisTwo). Ie, the part in parentheses is evaluated, which returns an anonymous function, which is then invoked. My expectation then is that this would be Window, not obj.
Is this a special case, or is my understanding of how this is resolved faulty?
(Edited to make the reason for my confusion clearer)
Yes. The value of the this context of a call depends on the type of the function invocation.
In your case, it's a method invocation - a function that is called by a property reference. And yes, parentheses do not evaluate a property reference.
See also Nature of JS bound functions and function invocation operator and this very good answer for details.

Categories

Resources