Here is my object construction,
function Employee(name, dob) {
this.Name = name;
this.DateOfBirth = new Date(dob);
}
Now, I have created an instance for this, like
var emp = new Employee("sample","12/12/12");
Its working fine when i print the output.
But, if i create the object like
var emp = new Employee(name = "sample");
or
var emp = new Employee(dob = "12/12/12");
its not working fine. In both the cases, the DateOfBirth field is invalid.
I need to define an object with optional parameters.
JavaScript does not support named optional parameters.
When you do var emp = new Employee(name = "sample");
You're declaring a name global variable, assigning sample to it and passing that to the new call.
You can use objects to accomplish similar syntax in JS:
var emp = new Employee({name:"sample"});
Where the Employee function becomes:
function Employee(options) {
this.Name = options.name;
if(options.dob !== undefined){
this.DateOfBirth = new Date(options.dob);
}
}
Worth mentioning, in practice, you often don't need an Employee class, and can simply do:
var emp = {name:"sample"};
Or:
var emp = {dob:new Date("12/12/12");}
So unless Employee grows to become a real model (and has more than just two fields) I think that you might want to consider that.
function Employee(params) {
if (typeof params != "undefined") {
this.Name = (typeof params.name != "undefined") ? params.name : "";
this.DateOfBirth = (typeof params.dob != "undefined") ? new Date(params.dob) : null;
}
}
new Employee({
name: "John",
dob: "12/12/12"
});
new Employee({
name: "John"
});
new Employee({
dob: "12/12/12"
});
or using simple statements using ||.
function Employee(params) {
params = params || {};
this.Name = params.name || "";
this.DateOfBirth = new Date(params.dob || "");
}
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