What is the 'typeof define ===' function '&& define [' amd ']' for?

What is the purpose of the following code? What does the factory function do here? Here root is a window object. Is factory default java script function? In what scenarios can this type of code be used. This code is from toggle.js from Simon Tabor . Zepto and ender are libraries. It is mainly used in libraries.

if (typeof define === 'function' && define['amd']) { define(['jquery'], factory); } else { factory(root['jQuery'] || root['Zepto'] || root['ender'] || root['$']|| $); } 
+6
source share
1 answer

This code checks for the existence of the require.js JavaScript dependency management library.

If 'define' is not undefined, and this is a function, and 'amd' (asynchronous module definition) is also defined, then the code assumes that require.js is in the game.

If so, it defines a "factory" and passes jQuery to it as a dependency. Otherwise, it sets up the dependencies necessary for the code, attaching them to the root object.

As for the "factory": it is not defined by the Javascript infrastructure, most likely it will be a function in the same file. It will accept the jQuery parameter.

+14
source

Source: https://habr.com/ru/post/989442/


All Articles