For example, I already have this object somewhere in the code, it is a generic object:
var person1={lastName:"Freeman",firstName:"Gordon"};
I have the constructor for a Person object:
function Person(){ this.getFullName=function(){ return this.lastName + ' ' + this.firstName; } }
Is there a simple syntax that allows us to convert person1 to an object of type Person?
In JavaScript, there is the ability to create a generic anonymous object to serve this purpose. It can either be created using new Object() or the shorthand { ... } syntax, and can then be given any properties or methods that are needed.
If we want to cast the object to string data types by using toString() method we can change the object type to a string data type. We can also cast the object type to jsonby using json. parse() method we can get only the plain objects and it not used on the class object.
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]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With