Reputation: 1112
This question has probably been asked before, but I don't really know the proper keywords to find a solution on Google, so all my researches returned 0
:) Or better, all my researches ended up with "optional parameters" but for functions.
Let's assume I have this class:
var Class = function (params) {
// I get the data somehow
params.name(data);
}
The problem is that not every time I instantiate new Class()
I need also to set name()
like:
new Class({
name: function (data) {
// Do something with the data
}
... other params ...
})
But, with the above syntax, if I don't declare name parameter as a function, an error params.name is not a function
is thrown:
// Error
new Class({
... other params ...
})
My question is: is there a way to set params.name()
as an optional parameter (in the object) that can be a function or completely not exist (e.g. null
)? Something like saying: "when you instantiate the class:
name: function (data) {}
=> then: params.name(data)
is a functionname
=> it's anyway ok (no error is thrown)"Upvotes: 3
Views: 148
Reputation: 5023
In ES6, You can use default function parameter option, like
var Class = function(params = {
name: (x) => x
}) {
// I get the data somehow
data='value';
params.name(data);
}
Class();
Class({name: x => console.log(x)});
Hope this will help!
EDIT
Yes @brigo, you are right, sorry I overlooked that point. We are actually looking for nested default rather. A possible solution could be to destructure the object inside the function like
var Class = function(params = {}) {
// I get the data somehow
data = 'value';
withDefaultParams = {
name: (x) => x,
...params
}
withDefaultParams.name(data);
}
Class();
Class({
name: x => console.log('non-default')
});
Class({
others: x => console.log('non-default')
});
Upvotes: 3
Reputation: 2206
If using jQuery is an option, you could use its extend
method (API docs) like in the following example:
var Class = function(params) {
var _defaults = {
name: function(){},
some: 'other stuff'
};
params = jQuery.extend(_defaults,params);
// I get the data somehow
data='value';
params.name(data);
}
Class();
Class({foo:'bar'});
Class({name: console.log });
Upvotes: 0
Reputation: 2206
yes, you could do something like
if (typeof param.name === 'function') {
param.name(data);
} else {
// dont do anything or do something different
}
Upvotes: 2