关于JavaScript中function关键字的使用困惑及new function用法疑问
new function() in JavaScript Great question—this is one of those quirky JavaScript nuances that trips up a lot of self-taught developers (trust me, I’ve been there too!). Let’s break this down step by step.
Why use new with this function?
First, let’s clarify what new function() actually does: it’s a shortcut for defining an anonymous constructor function AND instantiating it in one line.
Normally, you’d create a reusable constructor like this:
function Person(name) { this.name = name; } const alice = new Person("Alice");
With new function(), you’re skipping the step of naming and storing the constructor—you define it anonymously and immediately create an instance from it.
The new keyword here is critical because:
- Without
new, callingfunction(){}would just run it as a regular function. In non-strict mode,thiswould point to the global object (e.g.,windowin browsers), and the function would returnundefined(unless you explicitly return something). - With
new, JavaScript creates a brand new empty object, bindsthisto that object inside the function, and automatically returns the object (even if you don’t have areturnstatement).
Here’s a side-by-side comparison to make it clear:
// Regular function call (no new) const noNew = function() { this.foo = "bar"; }; console.log(noNew()); // undefined (and in non-strict mode, window.foo becomes "bar"—oops!) // With new const withNew = new function() { this.foo = "bar"; }; console.log(withNew.foo); // "bar" (we get a proper instance object)
Why isn’t the function capitalized?
Capitalizing constructor functions (like Person, Array, Date) is just a widely accepted convention in JavaScript. The goal is to signal to other developers: “Hey, this function is meant to be used with new!”
But new function() is an anonymous function that’s only used once—you’re not storing it in a variable to reuse as a constructor later. Since it’s not a reusable blueprint for multiple instances, there’s no need to follow the capitalization convention. It’s a one-off, so the lowercase f is totally acceptable.
A common use case for new function()
Back in the day, before ES6 classes and private class fields, this pattern was often used to create objects with private variables (thanks to closures):
const secretHolder = new function() { // This variable is private—can't access it from outside const topSecret = "I love pizza"; // Expose a method to access the private value this.revealSecret = function() { return topSecret; }; }; console.log(secretHolder.revealSecret()); // "I love pizza" console.log(secretHolder.topSecret); // undefined (can't reach it!)
Nowadays, we’d probably use # private fields in a class instead, but understanding this pattern helps you grok JavaScript’s prototype and closure fundamentals.
内容的提问来源于stack exchange,提问作者Junior




