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

后端 未结 6 1323
暖寄归人
暖寄归人 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:27

    This worked for me. It's simple for simple objects.

    class Person {
      constructor(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
      }
      getFullName() {
        return this.lastName + " " + this.firstName;
      }
    
      static class(obj) {
        return new Person(obj.firstName, obj.lastName);
      }
    }
    
    var person1 = {
      lastName: "Freeman",
      firstName: "Gordon"
    };
    
    var gordon = Person.class(person1);
    console.log(gordon.getFullName());

    I was also searching for a simple solution, and this is what I came up with, based on all other answers and my research. Basically, class Person has another constructor, called 'class' which works with a generic object of the same 'format' as Person. I hope this might help somebody as well.

提交回复
热议问题