简体   繁体   中英

Javascript object options: function or null

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 (eg null )? Something like saying: "when you instantiate the class:

  • if you declare name: function (data) {} => then: params.name(data) is a function
  • if you skip name => it's anyway ok (no error is thrown)"

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') }); 

yes, you could do something like

if (typeof param.name === 'function') {
    param.name(data);
} else {
    // dont do anything or do something different
}

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 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM