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

前端 未结 4 1408
粉色の甜心
粉色の甜心 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 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();
    

提交回复
热议问题