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
?
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.
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.
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With