Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 556
bobo Avatar asked Jan 05 '12 02:01

bobo


People also ask

How can generic objects be created JavaScript?

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.

How do I cast objects in typescript?

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.


1 Answers

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

like image 116
A1rPun Avatar answered Sep 28 '22 02:09

A1rPun