Use of .apply() with 'new' operator. Is this possible?

后端 未结 30 3157
Happy的楠姐
Happy的楠姐 2020-11-22 00:39

In JavaScript, I want to create an object instance (via the new operator), but pass an arbitrary number of arguments to the constructor. Is this possible?

30条回答
  •  轮回少年
    2020-11-22 00:59

    While the other approaches are workable, they're unduly complex. In Clojure you generally create a function that instantiates types/records and use that function as the mechanism for instantiation. Translating this to JavaScript:

    function Person(surname, name){
      this.surname = surname;
      this.name = name;
    }
    
    function person(surname, name){ 
      return new Person(surname, name);
    }
    

    By taking this approach you avoid the use of new except as described above. And this function, of course, has no issues working with apply or any number of other functional programming features.

    var doe  = _.partial(person, "Doe");
    var john = doe("John");
    var jane = doe("Jane");
    

    By using this approach, all of your type constructors (e.g. Person) are vanilla, do-nothing constructors. You just pass in arguments and assign them to properties of the same name. The hairy details go in the constructor function (e.g. person).

    It is of little bother having to create these extra constructor functions since they are a good practice anyhow. They can be convenient since they allow you to potentially have several constructor functions with different nuances.

提交回复
热议问题