Javascript Constructor - Use An Object?
I'm trying to create a new object by using an already made object. This is what I am trying to achieve: var obj = {'Name' : 'Patrick', 'Age': 25, 'Country': 'US'}; document.writeln
Solution 1:
You have plenty of options here.
For example you could make your Person
polymorphic on arguments it takes.
functionPerson(name, age, country) {
if(arguments.length === 1 && typeof name === 'object') {
var data = arguments[0];
name = data.name; //etc
}
//the rest of ctor code goes here
}
Or BETTER use factory function and keep your constructor code as simple is possible
functioncopyPerson(obj) {
returnnewPerson(obj.name, obj.age, obj.country);
}
//or evenPerson.copy = function(obj) {
returnnewthis(obj.name, obj.age, obj.country)
}
Solution 2:
This is what you could do to support both the input formats:
function Person(name, age, country) {
var obj;
if(typeof(name) === 'object'){
obj = name;
name = obj.name;
age = obj.age;
country = obj.country;
}
this.name = name;
this.age = age;
this.country = country;
}
Solution 3:
var Person = function(nameOrObj, age, country) {
if (typeof nameOrObj === 'object') {
this.name = nameOrObj.name
this.age = nameOrObj.age
this.country = nameOrObj.country
} else {
this.name = nameOrObj
this.age = age
this.country = country
}
}
Post a Comment for "Javascript Constructor - Use An Object?"