My question is regarding the resulting object from using new function(){ ... }
over new Function();
My understanding so far/assumption
My question
Following my assumption above, why does new Function();
and new function(){ ... }
return different things?
The first returns a function object, but the latter returns a standard object. Given that a function expression under the hood uses the Function() constructor, why does the latter not behave the same as new Function();
?
Using new function(){ ...}
I would expect a function object, not a standard object.
The following lines are essentially the same:
function foo(...) {...}
var foo = function (...) {...};
var foo = new Function (...);
They all declare a new function (which is an object, that is an instance of Function
, which inherits the Object
prototype, ...) in the current scope which can be accessed via the foo
variable.
The new
keyword instantiates an object from a function which allows you to create something similar to a class instance in a standard OOP language.
Continuing the example from above:
var bar = new foo(...)
would instantiate an instance of the foo
function in the current scope which could be accessed via the bar
variable.
why does
new Function();
andnew function(){ ... }
return different things?
I'm going to rephrase the example slightly. Instead of:
new Function()
//and
new function(){ ... }
I'm going to use
new Function()
//and
var foo = function () { ... };
new foo();
The reason that new Function()
returns a different thing than new foo()
is entirely because Function
is a different function from foo
.
I expect that you're not confused by the fact that new Object()
returns a different object with different features than new Array()
. The exact same thing is happening here.
Given that a function expression under the hood uses the
Function()
constructor, why does the latter not behave the same asnew Function();
?
under the hood the later expression is essentially:
new (new Function ( ... ))
new Function(...) returns a new function , while new function() {...} returns a new Object .
Basically, Function is just a way to evaluate a piece of code.
Objects are a way, to store data in javascript.
Side note: you can technically do
new (new Function(...))
wich returns a new object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.