[removed] How to create a new instance of a class without using the new keyword?

后端 未结 6 2123
死守一世寂寞
死守一世寂寞 2020-12-25 13:22

I think the following code will make the question clear.

// My class
var Class = function() { console.log(\"Constructor\"); };
Class.prototype = { method: fu         


        
6条回答
  •  时光说笑
    2020-12-25 13:31

    A simpler, cleaner way with no "factories"

    function Person(name) {
      if (!(this instanceof Person)) return new Person(name);
      this.name = name;
    }
    
    var p1 = new Person('Fred');
    var p2 = Person('Barney');
    
    p1 instanceof Person  //=> true
    p2 instanceof Person  //=> true
    

提交回复
热议问题