Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "new" still not recommended in JavaScript?

So I see plenty of JavaScript code out there that uses "new" when making constructors. After reading part of JavaScript the Good Parts it seems that using "new" isn't the cat's pajamas. That was 4 years ago though... Is it still not recommended? What is the current standard?

like image 446
Parris Avatar asked Aug 09 '12 07:08

Parris


People also ask

Should you use new in JavaScript?

It is NOT 'bad' to use the new keyword. But if you forget it, you will be calling the object constructor as a regular function. If your constructor doesn't check its execution context then it won't notice that 'this' points to different object (ordinarily the global object) instead of the new instance.

What is new used for in JavaScript?

The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

How do you create a new function in JavaScript?

The syntax for creating a function: let func = new Function ([arg1, arg2, ... argN], functionBody); The function is created with the arguments arg1...

Why this keyword is undefined in JavaScript?

A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .


2 Answers

Since when is new not recommended? D. Crockford has a valid point and a strong opinion but new is part of the language and it's very much being used in many projects. new is part of the prototype inheritance model, and must be used to create new instances with a constructor function. Crockford points out a purely functional approach using the this context appropriately and return this to be able to inherit properties and methods between children objects. It's a different solution to a common problem, but it doesn't mean that new shouldn't be used. In fact, one of the most copy/pasted JS snippets of all times is Crockford's, the object.create polyfill, and it uses new:

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
} 
like image 139
elclanrs Avatar answered Sep 27 '22 22:09

elclanrs


Nothing much has changed since 2008 apart from the Crockford-influenced Object.create making its way into ECMAScript 5: new still has the same behaviour and drawbacks that Douglas Crockford has forcefully pointed out. My own opinion is that he has rather overstated the problems and turned developers against a useful operator, so I continue to use it without issue; I would suggest other developers make up their own mind rather than blindly internalize and regurgitate (the admittedly admirable) Crockford.

like image 44
Tim Down Avatar answered Sep 27 '22 22:09

Tim Down