Can we cast a generic object to a custom object type in javascript?

后端 未结 6 1325
暖寄归人
暖寄归人 2021-01-31 13:46

For example, I already have this object somewhere in the code, it is a generic object:

var person1={lastName:\"Freeman\",firstName:\"Gordon\"};

6条回答
  •  长情又很酷
    2021-01-31 14:25

    This is not exactly an answer, rather sharing my findings, and hopefully getting some critical argument for/against it, as specifically I am not aware how efficient it is.

    I recently had a need to do this for my project. I did this using Object.assign, more precisely it is done something like this:Object.assign(new Person(...), anObjectLikePerson).

    Here is link to my JSFiddle, and also the main part of the code:

    function Person(firstName, lastName) {
      this.firstName = firstName;
      this.lastName = lastName;
    
      this.getFullName = function() {
        return this.lastName + ' ' + this.firstName;
      }
    }
    
    var persons = [{
      lastName: "Freeman",
      firstName: "Gordon"
    }, {
      lastName: "Smith",
      firstName: "John"
    }];
    
    var stronglyTypedPersons = [];
    for (var i = 0; i < persons.length; i++) {
      stronglyTypedPersons.push(Object.assign(new Person("", ""), persons[i]));
    }
    

提交回复
热议问题