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
我们现在需要写一个 foo 函数,这个函数返回首次调用时的 Date 对象,注意是首次。
var foo = function() { var t = new Date(); foo = function() { return t; }; return foo(); };
DOM 事件添加中,为了兼容现代浏览器和 IE 浏览器,我们需要对浏览器环境进行一次判断:
// 简化写法 function addEvent (type, el, fn) { if (window.addEventListener) { el.addEventListener(type, fn, false); } else if(window.attachEvent){ el.attachEvent('on' + type, fn); } }
缺点:每次调用 addEvent 时都会进行一次判断。 惰性函数:
function addEvent (type, el, fn) { if (window.addEventListener) { addEvent = function (type, el, fn) { el.addEventListener(type, fn, false); } } else if(window.attachEvent){ addEvent = function (type, el, fn) { el.attachEvent('on' + type, fn); } } }
闭包:
var addEvent = (function(){ 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); } } })();
当我们每次都需要进行条件判断,如果只需要判断一次,接下来的使用方式都不会发生改变的时候,想想是否可以考虑使用惰性函数。
The text was updated successfully, but these errors were encountered:
No branches or pull requests
需求
我们现在需要写一个 foo 函数,这个函数返回首次调用时的 Date 对象,注意是首次。
更多应用
DOM 事件添加中,为了兼容现代浏览器和 IE 浏览器,我们需要对浏览器环境进行一次判断:
缺点:每次调用 addEvent 时都会进行一次判断。
惰性函数:
闭包:
总结
当我们每次都需要进行条件判断,如果只需要判断一次,接下来的使用方式都不会发生改变的时候,想想是否可以考虑使用惰性函数。
参考
The text was updated successfully, but these errors were encountered: