JS学习20(高级技巧)

前端开发 作者: 2024-08-25 19:35:02
高级函数函数本质上是很简单且过程化的,但是由于JS天生的动态的特性,从使用方式上可以很复杂。安全的类型检测虽然JS中是有类型检测的,但是由于浏览器实现等它们并不完全可靠。比如typeof在Safari中对正则表达式也返回function。 instanceof在存在多个全局作用域时也会把同种却不同作

高级函数

var isArray = value instanceof Array;
function isArray(value){ return Object.prototype.toString.call(value) == "[object Array]"; } function isFunction(value){ return Object.prototype.toString.call(value) == "[object Function]"; } function isRegExp(value){ return Object.prototype.toString.call(value) == "[object RegExp]"; }
var isNativeJSON = window.JSON && Object.prototype.toString.call(JSON) == "[object JSON]";
function Person(name,age,job){ this.name = name; this.age = age; this.job = job; } var person = new Person("Nicholas",29,"Software Engineer");
function Person(name,job){ if (this instanceof Person){ this.name = name; this.age = age; this.job = job; } else { return new Person(name,job); } } var person1 = Person("Nicholas","Software Engineer"); alert(window.name); //"" alert(person1.name); //"Nicholas" var person2 = new Person("Shelby",34,"Ergonomist"); alert(person2.name); //"Shelby"
function Polygon(sides){ if (this instanceof Polygon) { this.sides = sides; this.getArea = function(){ return 0; }; } else { return new Polygon(sides); } } function Rectangle(width,height){ //这里调用时,传进去的this是Rectangle类型的,没办法拓展side属性 Polygon.call(this,2); this.width = width; this.height = height; this.getArea = function(){ return this.width * this.height; }; } var rect = new Rectangle(5,10); alert(rect.sides); //undefined
Rectangle.prototype = new Polygon(); var rect = new Rectangle(5,10); alert(rect.sides); //2
function createXHR(){ if (typeof XMLHttpRequest != "undefined"){ return new XMLHttpRequest(); } else if (typeof ActiveXObject != "undefined"){ if (typeof arguments.callee.activeXString != "string"){ var versions = ["MSXML2.XMLHttp.6.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp"],i,len; for (i=0,len=versions.length; i < len; i++){ try { new ActiveXObject(versions[i]); arguments.callee.activeXString = versions[i]; break; } catch (ex){ } } } return new ActiveXObject(arguments.callee.activeXString); } else { throw new Error("No XHR object available."); } }
function createXHR(){ if (typeof XMLHttpRequest != "undefined"){ createXHR = function(){ return new XMLHttpRequest(); }; } else if (typeof ActiveXObject != "undefined"){ createXHR = function(){ if (typeof arguments.callee.activeXString != "string"){ var versions = ["MSXML2.XMLHttp.6.0",len; for (i=0,len=versions.length; i < len; i++){ try { new ActiveXObject(versions[i]); arguments.callee.activeXString = versions[i]; break; } catch (ex){ //skip } } } return new ActiveXObject(arguments.callee.activeXString); }; } else { createXHR = function(){ throw new Error("No XHR object available."); }; } return createXHR(); } createXHR(); alert(createXHR);
var createXHR = (function(){ if (typeof XMLHttpRequest != "undefined"){ return function(){ return new XMLHttpRequest(); }; } else if (typeof ActiveXObject != "undefined"){ return function(){ if (typeof arguments.callee.activeXString != "string"){ var versions = ["MSXML2.XMLHttp.6.0",len=versions.length; i < len; i++){ try { new ActiveXObject(versions[i]); arguments.callee.activeXString = versions[i]; break; } catch (ex){ //skip } } } return new ActiveXObject(arguments.callee.activeXString); }; } else { return function(){ throw new Error("No XHR object available."); }; } })(); alert(createXHR);
var handler = { message: "Event handled",handleClick: function(event){ alert(this); alert(this.message); } }; var btn = document.getElementById("myButton"); EventUtil.addHandler(btn,"click",handler.handleClick); //[object HTMLButtonElement] undefined handler.handleClick(); // [object Object] Event handled
var handler = { message: "Event handled",handleClick: function(event){ alert(this); // [object Object] alert(this.message); // Event handled } }; var btn = document.getElementById("myButton"); EventUtil.addHandler(btn,function(event){ alert(this); //[object HTMLButtonElement] handler.handleClick(event); });
function bind(fn,context){ alert(arguments[0]); //fn本身 return function(){ alert(arguments[0]); //event return fn.apply(context,arguments); }; }
var handler = { message: "Event handled",handleClick: function(event){ alert(this); // [object Object] alert(this.message); // Event handled } }; var btn = document.getElementById("myButton"); EventUtil.addHandler(btn,bind(handler.handleClick,handler));
EventUtil.addHandler(btn,handler.handleClick.bind(handler));
function add(num1,num2){ return num1 + num2; } function curriedAdd(num2){ return add(5,num2); } alert(add(2,3)); //5 alert(curriedAdd(3)); //8
function curry(fn){ var args = Array.prototype.slice.call(arguments,1); return function(){ var innerArgs = Array.prototype.slice.call(arguments); var finalArgs = args.concat(innerArgs); return fn.apply(null,finalArgs); }; }
function add(a,b) { alert(a); alert(b); alert(a+b); } var curriedAdd = curry(add,5); curriedAdd(3); //8 curriedAdd = curry(add,3); curriedAdd(5); //8 curriedAdd = curry(add,5,3); curriedAdd(); //8
function bind(fn,context){ var args = Array.prototype.slice.call(arguments,2); return function(){ var innerArgs = Array.prototype.slice.call(arguments); var finalArgs = args.concat(innerArgs); return fn.apply(context,finalArgs); }; } var handler = { message: "Event handled",handleClick: function(name,event){ alert(this.message + ":"+ name + ":"+ event.type); } }; var btn = document.getElementById("myButton"); EventUtil.addHandler(btn,handler,"myButton"));
EventUtil.addHandler(btn,handler.handleClick.bind(handler,"myButton"));

防篡改对象

var person = { name: "Nicholas" }; Object.preventExtensions(person); person.age = 29; alert(person.age); //undefined alert(Object.isExtensible(person)); //false person.name = "hahah"; alert(person.name); //hahah
var person = { name: "Nicholas" }; Object.seal(person); person.age = 29; alert(person.age); //undefined delete person.name; alert(person.name); //"Nicholas" alert(Object.isExtensible(person)); //false alert(Object.isSealed(person)); //true
var person = { name: "Nicholas" }; Object.freeze(person); person.age = 29; alert(person.age); //undefined delete person.name; alert(person.name); //"Nicholas" person.name = "Greg"; alert(person.name); //"Nicholas" alert(Object.isExtensible(person));//false alert(Object.isSealed(person));//true alert(Object.isFrozen(person));//true

高级定时器

setTimeout(function(){ setTimeout(arguments.callee,interval); },interval);
function chunk(array,process,context){ setTimeout(function(){ var item = array.shift(); process.call(context,item); if (array.length > 0){ setTimeout(arguments.callee,100); } },100); } var data = [12,123,1234,453,436,23,4123,45,346,5634,2234,345,342]; function printValue(item){ var div = document.getElementById("myDiv"); div.innerHTML += item + "<br>"; } chunk(data,printValue);
function throttle(method,context) { clearTimeout(method.tId); method.tId= setTimeout(function(){ method.call(context); },100); } function reDiv(){ var div = document.getElementById("myDiv"); div.innerHTML += "qqqqqq" + "<br>"; } window.onresize = function(){ throttle(reDiv); };

自定义事件

function EventTarget(){ this.handlers = {}; } EventTarget.prototype = { constructor: EventTarget,addHandler: function(type,handler){ if (typeof this.handlers[type] == "undefined"){ this.handlers[type] = []; } this.handlers[type].push(handler); },fire: function(event){ if (!event.target){ event.target = this; } if (this.handlers[event.type] instanceof Array){ var handlers = this.handlers[event.type]; for (var i=0,len=handlers.length; i < len; i++){ handlers[i](event); } } },removeHandler: function(type,handler){ if (this.handlers[type] instanceof Array){ var handlers = this.handlers[type]; for (var i=0,len=handlers.length; i < len; i++){ if (handlers[i] === handler){ break; } } handlers.splice(i,1); } } };
function handleMessage(event){ alert("Message received: " + event.message); } var target = new EventTarget(); target.addHandler("message",handleMessage); target.fire({ type: "message",message: "Hello world!"}); target.removeHandler("message",message: "Hello world!"});

拖放

var DragDrop = function(){ var dragging = null; var diffX = 0; var diffY = 0; function handleEvent(event){ event = EventUtil.getEvent(event); var target = EventUtil.getTarget(event); switch(event.type){ case "mousedown": if (target.className.indexOf("draggable") > -1){ dragging = target; diffX = event.clientX - target.offsetLeft; diffY = event.clientY - target.offsetTop; } break; case "mousemove": if (dragging !== null){ dragging.style.left = (event.clientX - diffX) + "px"; dragging.style.top = (event.clientY - diffY) + "px"; } break; case "mouseup": dragging = null; break; } }; return { enable: function(){ EventUtil.addHandler(document,"mousedown",handleEvent); EventUtil.addHandler(document,"mousemove","mouseup",handleEvent); },disable: function(){ EventUtil.removeHandler(document,handleEvent); EventUtil.removeHandler(document,handleEvent); } } }(); DragDrop.enable();
var DragDrop = function(){ //这里的dragdrop是之前的EventTarget类型,可以用来保存和触发事件 var dragdrop = new EventTarget(),dragging = null,diffX = 0,diffY = 0; function handleEvent(event){ event = EventUtil.getEvent(event); var target = EventUtil.getTarget(event); switch(event.type){ case "mousedown": if (target.className.indexOf("draggable") > -1){ dragging = target; diffX = event.clientX - target.offsetLeft; diffY = event.clientY - target.offsetTop; //触发自定义事件 dragdrop.fire({type:"dragstart",target: dragging,x: event.clientX,y: event.clientY}); } break; case "mousemove": if (dragging !== null){ dragging.style.left = (event.clientX - diffX) + "px"; dragging.style.top = (event.clientY - diffY) + "px"; dragdrop.fire({type:"drag",y: event.clientY}); } break; case "mouseup": dragdrop.fire({type:"dragend",y: event.clientY}); dragging = null; break; } }; dragdrop.enable = function(){ EventUtil.addHandler(document,handleEvent); EventUtil.addHandler(document,handleEvent); }; dragdrop.disable = function(){ EventUtil.removeHandler(document,handleEvent); EventUtil.removeHandler(document,handleEvent); }; return dragdrop; }(); DragDrop.addHandler("dragstart",function(event){ var status = document.getElementById("myDiv"); status.innerHTML = "Started dragging " + event.target.id; }); DragDrop.addHandler("drag",function(event){ var status = document.getElementById("myDiv"); status.innerHTML += "<br/> Dragged " + event.target.id + " to (" + event.x + "," + event.y + ")"; }); DragDrop.addHandler("dragend",function(event){ var status = document.getElementById("myDiv"); status.innerHTML += "<br/> Dropped " + event.target.id + " at (" + event.x + "," + event.y + ")"; }); DragDrop.enable();
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_68563.html