简体   繁体   中英

Nodejs module.exports and Shorthand if/else

What does the line 'undefined' != typeof Customer ? Customer : module.exports 'undefined' != typeof Customer ? Customer : module.exports in the following code snippet do? And why do you wrap everything within (function(){}) ? I cant seem to decipher its meaning

This snippet comes from a library file.

(function (Customer) {

  Customer.Base = {
    //...
  }

})(
  'undefined' != typeof Customer ? Customer : module.exports

);

This is ternary that is used to determine what is passed to the function. The function is an Immediately-invoked function exppression (IIFE) - a function that is created and immediately invoked.

//the condition
'undefined' != typeof Customer
//true value
? Customer 
//false value
: module.exports

If Customer is undefined, this is the same result:

(function (Customer) {

  Customer.Base = {
    //...
  }

})(module.exports);

So this code block is creating and immediately invoking a function that does something to a Customer . If Customer is defined, Customer is passed to the function as the function argument which is also named Customer . If Customer is undefined, module.exports is passed to the function as the Customer argument. This code could be rewritten as:

var param;
if ('undefined' != typeof Customer) {
  param = Customer;
} else {
  param = module.exports;
}

function myFunc(Customer) {

  Customer.Base = {
    //...
  }

}

myFunc(param);

It may be easier to understand in a more generic example.

Here's an IIFE, a function that is created and immediately invoked: Live demo (click).

(function(param) {
    console.log(param);
})('some param!');

and here's that same function, using ternary to determine the param value: Live demo (click).

var x = true;
//var x = false;

var value = x ? 'true value!' : 'false value!';

(function(param) {
    console.log(param);
})(value);

Change x (the condition) to true or false and see that the assigned value of value is changed accordingly.

You may often see the ternary condition wrapped in () , but they are not necessary:

('undefined' != typeof Customer) ? Customer : module.exports

Further, it is more typical to see that statement asked the opposite way:

typeof Customer === 'undefined'

and it is likely that a simple loose equality check for "truthiness" would suffice here:

Customer ? Customer : module.exports

and that could again be simplified to:

Customer || module.exports
//if "Customer" is truthy, it will be used, otherwise, module.exports is used

Also note that with an IIFE, the can be })() or {()) , the latter being the more typical syntax.

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