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

后端 未结 2 1799
不思量自难忘°
不思量自难忘° 2021-02-13 04:54

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

相关标签:
2条回答
  • 2021-02-13 05:35

    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.

    0 讨论(0)
  • 2021-02-13 05:36

    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.

    0 讨论(0)
提交回复
热议问题