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

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)