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

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

    The answer of @PeterOlson may be worked back in the day but it looks like Object.create is changed. I would go for the copy-constructor way like @user166390 said in the comments.
    The reason I necromanced this post is because I needed such implementation.

    Nowadays we can use Object.assign (credits to @SayanPal solution) & ES6 syntax:

    class Person {
      constructor(obj) {
        obj && Object.assign(this, obj);
      }
    
      getFullName() {
        return `${this.lastName} ${this.firstName}`;
      }
    }
    

    Usage:

    const newPerson = new Person(person1)
    newPerson.getFullName() // -> Freeman Gordon
    

    ES5 answer below

    function Person(obj) {
        for(var prop in obj){
            // for safety you can use the hasOwnProperty function
            this[prop] = obj[prop];
        }
    }
    

    Usage:

    var newPerson = new Person(person1);
    console.log(newPerson.getFullName()); // -> Freeman Gordon
    

    Using a shorter version, 1.5 liner:

    function Person(){
        if(arguments[0]) for(var prop in arguments[0]) this[prop] = arguments[0][prop];
    }
    

    jsfiddle

提交回复
热议问题