Is JavaScript's “new” keyword considered harmful?

前端 未结 12 2205
情书的邮戳
情书的邮戳 2020-11-21 23:18

In another question, a user pointed out that the new keyword was dangerous to use and proposed a solution to object creation that did not use new.

12条回答
  •  日久生厌
    2020-11-21 23:41

    I think new is evil, not because if you forget to use it by mistake it might cause problems but because it screws up the inheritance chain, making the language tougher to understand.

    JavaScript is prototype-based object-oriented. Hence every object MUST be created from another object like so var newObj=Object.create(oldObj). Here oldObj is called the prototype of newObj (hence "prototype-based"). This implies that if a property is not found in newObj then it will be searched in oldObj. newObj by default will thus be an empty object but due to its prototype chain it appears to have all the values of oldObj.

    On the other hand if you do var newObj=new oldObj(), the prototype of newObj is oldObj.prototype, which is unnecessarily difficult to understand.

    The trick is to use

    Object.create=function(proto){
      var F = function(){};
      F.prototype = proto;
      var instance = new F();
      return instance;
    };
    

    It is inside this function and only here that new should be used. After this simply use the Object.create() method. The method resolves the prototype problem.

提交回复
热议问题