Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Crockford say not to use the new keyword if he advises us to use it for prototypal inheritance?

Tags:

javascript

I saw a video in which Crockford told us not to use the new keyword. He said to use Object.create instead if I'm not mistaken. Why does he tell us not to use new if he has used it in achieving prototypal inheritance in this article that he wrote: http://javascript.crockford.com/prototypal.html

I would expect him to use Object.create instead of new, like this:

function object(o) {
    return Object.create((function() {}).prototype = o);
}

So why is it that he still uses new?

like image 677
David G Avatar asked Nov 20 '11 16:11

David G


People also ask

What is prototypal inheritance in JavaScript?

The Prototypal Inheritance is a feature in javascript used to add methods and properties in objects. It is a method by which an object can inherit the properties and methods of another object. Traditionally, in order to get and set the [[Prototype]] of an object, we use Object. getPrototypeOf and Object.

What happens if you don't 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.

Should I use new in JS?

New keyword in JavaScript is used to create an instance of an object that has a constructor function. On calling the constructor function with 'new' operator, the following actions are taken: A new empty object is created.


2 Answers

Crockford discusses new and Object.create in this Nov 2008 message to the JSLint.com mailing list. An excerpt:

If you call a constructor function without the new prefix, instead of creating and initializing a new object, you will be damaging the global object. There is no compile time warning and no runtime warning. This is one of the language’s bad parts.

In my practice, I completely avoid use of new.

like image 196
Paul Beusterien Avatar answered Oct 20 '22 00:10

Paul Beusterien


This is a really old question, but…

When Crockford wrote the article you mention and the discussion linked by Paul Beusterien, there was no Object.create. It was 2008 and Object.create was, at most, a proposal (or really rarely implemented in browsers).

His final formulation is basically a polyfill:

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}

newObject = Object.create(oldObject);

His only use of new is, therefore, to simulate (or emulate) what Object.create must do.

He doesn’t advise us to use it. He presents a polyfill that uses it, so you don’t have to use it anywhere else.

like image 39
slacktracer Avatar answered Oct 19 '22 23:10

slacktracer