Foreword
Summarize the JavaScript syntax sugar that I have come across recently and share it with everyone.
Each piece of candy has detailed instructions and examples, so I won’t go into details.
Accurate type checking
/*
* @function:
* Type checking example
* Through this method, you can check whether a variable is the expected data type
* @params:
* obj variable to be checked, required
* config data type whitelist, optional, default is all types
* @return:
* true means the check passed, false means it failed
* @examples:
* typeCheck("str"); //return true
* typeCheck({},{"[object Array]": 1}); //return false
*/
function typeCheck(obj,config){
var hasOp = Object.prototype.hasOwnProperty,
toStr = Object.prototype.toString,
_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 hasOp.call(_config,toStr.call(obj));
}
Elegant way to add prototypes
/*
* @description:
* Elegant way to add prototypes
* Just execute this code snippet in the public scope
*/
if(typeof Function.prototype.method !== "function") {
Function.prototype.method = function(name,fn){
This.prototype[name] = fn;
Return this;
};
}
/*
* Usage example
*/
//Define a "test class"
function testFn(){
}
//Add member methods of the test class
testFn.method("add",function(a,b){
Return a b;
}).method("sub",function(a,b){
Return a - b;
});
//Instantiation
var testObj = new testFn();
//Call member method
testObj.add(1,5); //return 6
testObj.sub(7,2); //return 5
Quickly create namespace
/*
* @function:
* Create namespace
* @params:
* ex namespace expression, for example: NSROOT.service.impl
* This expression must be written starting from the root node
* @return:
* Returns Object, this Object is the last node of the expression
* @others:
* If you don’t like the name NSROOT, simply search and replace
*/
var NSROOT = NSROOT || {};
NSROOT.namespace = function(ex){
var _ex = ex || "",
nsArray = _ex.split("."),
parentNode = NSROOT,
_s = "",
i = 0;
//Determine whether the namespace starts from the root node
if(nsArray[0] !== "NSROOT"){
throw("The namespace must start from the root node!");
}
//Remove root node
nsArray = nsArray.slice(1);
for(i = 0;i
_s = nsArray[i];
If(parentNode[_s] === undefined){
parentNode[_s] = {};
}
parentNode = parentNode[_s];
}
Return parentNode;
};
/*
* Usage example
*/
//Create a new namespace
var impl = NSROOT.namespace("NSROOT.service.impl");
alert(impl === NSROOT.service.impl); //return true
//Create an existing namespace without overwriting the original data
NSROOT.namespace("NSROOT.service.impl");
alert(impl === NSROOT.service.impl); //return true