本文列出一些javascript常用的方法…
判断数据类型
1 2 3 4 5 6 7
| var isType = function(type){ return function(obj){ return Object.prototype.toString.call(obj) === '[object '+type+']'; } } var isArray = isType('Array')([1,2,3]); console.log(isArray);
|
还可以用循环语句来实现:
1 2 3 4 5 6 7 8 9
| var Type = {}; for (var i =0,type;type = ['String','Array','Number'][ i++ ];) { (function(type){ Type[ 'is' + type] = function(obj){ return Object.prototype.toString.call(obj) === '[object '+type+']'; } })(type) }; console.log(Type.isString([]));
|
懒性加载函数—添加事件
1 2 3 4 5 6 7 8 9 10 11 12
| var addEvent = function(elem,type,handler){ if(window.addEventListener){ addEvent = function(elem,type,handler){ elem.addEventListener(type,handler,false); } }else if(window.attachEvent){ addEvent = function(elem,type,handler){ elem.attachEvent('on'+type,handler); } } addEvent(elem,type,handler); };
|
调用例子:
1 2 3 4 5 6 7
| var div = document.getElementById('div'); addEvent(div,'click',function(){ alert(1); }); addEvent(div,'click',function(){ alert(2); });
|
分时函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| var timeChunk = function(ary, fn, count){ var obj, t; var len = ary.length; var start = function(){ for (var i =0; i<Math.min(count || 1,ary.length);i++) { var obj = ary.shift(); fn(obj); } }; return function(){ t = setInterval(function(){ if(ary.length === 0){ return clearInterval(t); } start(); },200); }; };
|
调用例子:
1 2 3 4 5 6 7 8 9 10
| var ary = []; for (var i =1;i<=1000;i++) { ary.push(i); }; var rendFriendList = timeChunk(ary,function(n){ var div = document.createElement('div'); div.innerHTML = n; document.body.appendChild(div); },8); rendFriendList();
|
单例模式—绑定一次事件(例如弹出登录框)
1 2 3 4 5 6
| var getSingle = function(fn){ var result; return function(){ return result || (result = fn.apply(this,arguments)); } };
|