SoFunction
Updated on 2025-04-10

Summary of common tips for JavaScript

Preface

I’ll summarize the JavaScript syntax sugar I’ve come into contact with recently and share it with you.

Each piece of candy has detailed instructions and examples, so I won’t say much.

Accurate type check

Copy the codeThe code is as follows:

 /*
 * @function:
*   Example of type checking
*  This method allows you to check whether a variable is the expected data type
 * @params:
*   obj variables that need to be checked, a must
*   config Data type whitelist, optional, default to all types
 * @return:
*   true means the check is passed, false failed
 * @examples:
 *   typeCheck("str"); //return true
 *   typeCheck({},{"[object Array]": 1}); //return false
 */
 function typeCheck(obj,config){
   var hasOp = ,
       toStr = ,
       _config = config || {
         "[object Object]": 1,
         "[object Array]": 1,
         "[object Regex]": 1,
         "[object String]": 1,
         "[object Number]": 1,
         "[object Boolean]": 1,
         "[object Function]": 1,
         "[object Undefined]": 1,
         "[object Null]": 1
       };
  
   return (_config,(obj));
 }

Elegant way to add prototypes

Copy the codeThe code is as follows:

 /*
 * @description:
*   Elegant way to add prototypes
*   Just execute this code snippet in the public scope
 */
 if(typeof !== "function") {
   = function(name,fn){
     [name] = fn;
     return this;
   };
 }
 /*
* Example of usage
 */
//Define a "test class"
 function testFn(){
 }
//Add a member method of the test class
 ("add",function(a,b){
   return a + b;
 }).method("sub",function(a,b){
   return a - b;
 });
//Instantiation
 var testObj = new testFn();
//Calling member method
 (1,5);  //return 6
 (7,2);  //return 5

Quickly create a namespace

Copy the codeThe code is as follows:

 /*
 * @function:
*   Create a namespace
 * @params:
*   ex namespace expression, for example:
*   This expression must be written from the root node
 * @return:
*   Returns an Object, which is the last node of the expression
 * @others:
*   If you don’t like the naming of NSROOT, simply search for the replacement
 */
 var NSROOT = NSROOT || {};
  = function(ex){
   var _ex = ex || "",
       nsArray = _ex.split("."),
       parentNode = NSROOT,
       _s = "",
       i = 0;
//Distinguish whether the namespace starts from the root node
   if(nsArray[0] !== "NSROOT"){
throw("The namespace must start from the root node!");
   }
//Remove the root node
   nsArray = (1);
   for(i = 0;i<;i++){
     _s = nsArray[i];
     if(parentNode[_s] === undefined){
       parentNode[_s] = {};
     }
     parentNode = parentNode[_s];
   }
   return parentNode;
 };
 /*
* Example of usage
 */
//Create a new namespace
 var impl = ("");
 alert(impl === );  //return true
//Create an existing namespace without overwriting the original data
 ("");
 alert(impl === );  //return true