Is JavaScript's "new" Keyword Truly Harmful?
Amidst the ongoing discussions on good JavaScript practices, Douglas Crockford's assertion that the "new" keyword poses a risk has sparked controversy. However, it's essential to delve deeper into its advantages and disadvantages before reaching a definite conclusion.
Advantages of Using "new"
Disadvantages of Using "new"
function foo() { if (!(this instanceof foo)) { return new foo(); } // Constructor logic follows... }
A Balanced Perspective
It's important to emphasize that Crockford's stance should not be blindly accepted. There are times when the benefits of "new" outweigh the potential drawbacks. By implementing the defensive programming mechanism described above, developers can harness the power of "new" without compromising the robustness of their code.
ES5/ES6 Considerations
In ES5, the use of "arguments.callee" in the defensive check is prohibited under strict mode. ES6 introduces a safe implementation of "new" within classes, eliminating the need for external checks. Additionally, "new.target" provides a check for constructors that are not called with "new."
Conclusion
While Crockford's concerns should be noted, the "new" keyword is not inherently harmful. By employing sensible coding practices and understanding its intricacies, developers can leverage the advantages of "new" while mitigating potential pitfalls. A balanced approach that considers both the benefits and the defensive techniques ensures the safe and effective utilization of this essential JavaScript feature.
The above is the detailed content of Is JavaScript's `new` Keyword Really That Dangerous?. For more information, please follow other related articles on the PHP Chinese website!