Does Javascript's new operator do anything but make life difficult?

前端 未结 4 1393
粉色の甜心
粉色の甜心 2020-12-28 18:21

I come from the traditional web developer background where I can by no means claim to really know anything about Javascript, however I am trying.

I currently have wh

相关标签:
4条回答
  • 2020-12-28 18:47

    Here's a great article on prototype.js's implementation of the typical OO structuring. This wouldn't be possible without the "new" operator.

    http://prototypejs.org/learn/class-inheritance

    I highly recommend reading the prototype.js source. jQuery is amazing, and highly popular, but some of the things that have been done in prototype just have no comparison** elsewhere, in particular their class structuring.

    **Some people might argue that some of what prototype does shouldn't be found elsewhere - that's a different question. But for sheer understanding of what's possible with javascript, prototype is the way to go, IMHO.

    0 讨论(0)
  • 2020-12-28 18:56

    There's nothing wrong with the new operator. To me, Crockford is unconvincing on the subject. Whenever you create an object you will either use new somewhere in your code or use it implicitly by creating literals (e.g. object literals such as {a: 1} or array literals such as [a, b, c]).

    0 讨论(0)
  • 2020-12-28 19:08

    First of all, kudos on reading Javascript: The Good Parts it's a great book on the language.

    To answer your question, the new operator is required if you want to make use of prototypal inheritance. There is no other way to have an object "inherit" from another. That being said, you can copy properties from one object to another that would remove the need for the operator in some cases.

    For example, a classical approach would use the following:

    function MyClass() {};
    MyClass.prototype.sayHello = function() {
       alert('hello');
    };
    
    
    var o = new MyClass();
    o.sayHello();
    

    You can achieve relatively the same thing as follows:

    function MyClass() {
       return { 
          sayHello: function() {
             alert('hello');
          }
       };
    }
    
    var o = MyClass();
    o.sayHello();
    
    0 讨论(0)
  • 2020-12-28 19:11

    You brought up Crockford's "JavaScript: The Good Parts."

    New is a bad part. Page 114. I don't use it. (Well, almost never.)

    Crockford does use it (in his beget() method).

    Definitely don't use it when you can use something else. Create objects and arrays with object and array literals.

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