We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
惰性函数就是解决每次都要进行判断的这个问题,解决原理很简单,重写函数。
var foo = function() { var t = new Date(); foo = function() { return t; }; return foo(); };
让我们看一下打印结果,是不是如此:
console.log("初始化:", foo); console.log("调用:", foo()); console.log("之后:", foo); // 初始化: ƒ () { // var t = new Date(); // foo = function() { // return t; // }; // return foo(); // } // 调用: Sun Apr 05 2020 17:17:41 GMT+0800 (中国标准时间) // 之后: ƒ () { // return t; // }
再比如 DOM 事件判断,每次都需要判断:
function addEvent(type, el, fn) { if (window.addEventListener) { el.addEventListener(type, fn, false); } else if (window.attachEvent) { el.attachEvent("on" + type, fn); } }
利用惰性函数,我们可以这样做:
function addEvent(type, el, fn) { if (window.addEventListener) { el.addEventListener(type, fn, false); addEvent = function(type, el, fn) { el.addEventListener(type, fn, false); }; } else if (window.attachEvent) { el.attachEvent("on" + type, fn); addEvent = function(type, el, fn) { el.attachEvent("on" + type, fn); }; } }
测试:
var container = document.getElementById("container"); console.log("初始化:", addEvent); var handle = function() { console.log("被触发了"); console.log("之后:", addEvent); }; addEvent("click", container, handle);
触发结果:
// 初始化: ƒ addEvent(type, el, fn) { // if (window.addEventListener) { // el.addEventListener(type, fn, false); // addEvent = function(type, el, fn) { // el.addEventListener(type, fn, false); // } // } else … // 被触发了 // 之后: ƒ (type, el, fn) { // el.addEventListener(type, fn, false); // }
使用闭包,初始化就完成对应事件:
var addEvent = (function(type, el, fn) { if (window.addEventListener) { return function(type, el, fn) { el.addEventListener(type, fn, false); } } else if (window.attachEvent) { return function(type, el ,fn) { el.attachEvent("on" + type, fn); } } })(); // 初始化: ƒ (type, el, fn) { // el.addEventListener(type, fn, false); // } // 被触发了 // 之后: ƒ (type, el, fn) { // el.addEventListener(type, fn, false); // }
学习资料:JavaScript专题之惰性函数
The text was updated successfully, but these errors were encountered:
No branches or pull requests
惰性函数
惰性函数就是解决每次都要进行判断的这个问题,解决原理很简单,重写函数。
让我们看一下打印结果,是不是如此:
再比如 DOM 事件判断,每次都需要判断:
利用惰性函数,我们可以这样做:
测试:
触发结果:
使用闭包,初始化就完成对应事件:
学习资料:JavaScript专题之惰性函数
The text was updated successfully, but these errors were encountered: