Reputation: 18408
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?
Upvotes: 5
Views: 384
Reputation: 324587
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.
Upvotes: 2
Reputation: 94101
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();
};
}
Upvotes: 6