Web程序員必備的7個(gè)JavaScript函數(shù)
數(shù)年前,只要我們編寫JavaScript,都必須用到幾個(gè)常用的函數(shù),比如,addEventListener 和 attachEvent,并不是為了很超前的技術(shù)和功能,只是一些基本的任務(wù),原因是各種瀏覽器之間的差異造成的。時(shí)間過去了這么久,技術(shù)在不斷的進(jìn)步,仍然有一些JavaScript函數(shù)是幾乎所有Web程序員必備的,或?yàn)榱诵阅埽驗(yàn)榱斯δ堋?/p>
防止高頻調(diào)用的debounce函數(shù)
這個(gè) debounce 函數(shù)對于那些執(zhí)行事件驅(qū)動(dòng)的任務(wù)來說是必不可少的提高性能的函數(shù)。如果你在使用scroll, resize, key*等事件觸發(fā)執(zhí)行任務(wù)時(shí)不使用降頻函數(shù),也行你就犯了重大的錯(cuò)誤。下面這個(gè)降頻函數(shù) debounce 能讓你的代碼變的高效:
// 返回一個(gè)函數(shù),that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. function debounce(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }; // Usage var myEfficientFn = debounce(function() { // All the taxing stuff you do }, 250); window.addEventListener('resize', myEfficientFn);
這個(gè) debounce 函數(shù)在給定的時(shí)間間隔內(nèi)只允許你提供的回調(diào)函數(shù)執(zhí)行一次,以此降低它的執(zhí)行頻率。當(dāng)遇到高頻觸發(fā)的事件時(shí),這樣的限制顯得尤為重要。
設(shè)定時(shí)間/頻率循環(huán)檢測函數(shù)
上面提到的 debounce 函數(shù)是借助于某個(gè)事件的觸發(fā)。但有時(shí)候并沒有這樣的事件可用,那我們只能自己寫一個(gè)函數(shù)來每隔一段時(shí)間檢查一次。
function poll (fn, callback, err, timeout, interval) { var startTime = (new Date()).getTime(); var pi = window.setInterval(function(){ if (Math.floor(((new Date).getTime() - startTime) / 1000) <= timeout) { if (fn()) { callback(); } } else { window.clearInterval(pi); err(); } }, interval) }
禁止重復(fù)調(diào)用、只允許執(zhí)行一次的once 函數(shù)
很多時(shí)候,我們只希望某種動(dòng)作只能執(zhí)行一次,就像是我們使用 onload 來限定只在加載完成時(shí)執(zhí)行一次。下面這個(gè)函數(shù)就能讓你的操作執(zhí)行一次后就不會(huì)再重復(fù)執(zhí)行。
function once(fn, context) { var result; return function() { if(fn) { result = fn.apply(context || this, arguments); fn = null; } return result; }; } // Usage var canOnlyFireOnce = once(function() { console.log('Fired!'); }); canOnlyFireOnce(); // "Fired!" canOnlyFireOnce(); // nada
這個(gè) once 函數(shù)能夠保證你提供的函數(shù)只執(zhí)行唯一的一次,防止重復(fù)執(zhí)行。
獲取一個(gè)鏈接的絕對地址 getAbsoluteUrl
獲取鏈接的絕對地址并不像你想象的那么簡單。下面就是一個(gè)非常實(shí)用的函數(shù),能根據(jù)你輸入的相對地址,獲取絕對地址:
var getAbsoluteUrl = (function() { var a; return function(url) { if(!a) a = document.createElement('a'); a.href = url; return a.href; }; })(); // Usage getAbsoluteUrl('/something');
這里使用了 a 標(biāo)簽 href 來生成完整的絕對URL,十分的可靠。
判斷一個(gè)JavaScript函數(shù)是否是系統(tǒng)原生函數(shù) isNative
很多第三方j(luò)s腳本都會(huì)在全局變量里引入新的函數(shù),有些甚至?xí)采w掉系統(tǒng)的原生函數(shù),下面這個(gè)方法就是來檢查是不是原生函數(shù)的:
;(function() { // Used to resolve the internal `[[Class]]` of values var toString = Object.prototype.toString; // Used to resolve the decompiled source of functions var fnToString = Function.prototype.toString; // Used to detect host constructors (Safari > 4; really typed array specific) var reHostCtor = /^\[object .+?Constructor\]$/; // Compile a regexp using a common native method as a template. // We chose `Object#toString` because there's a good chance it is not being mucked with. var reNative = RegExp('^' + // Coerce `Object#toString` to a string String(toString) // Escape any special regexp characters .replace(/[.*+?^${}()|[\]\/\\]/g, '\\$&') // Replace mentions of `toString` with `.*?` to keep the template generic. // Replace thing like `for ...` to support environments like Rhino which add extra info // such as method arity. .replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); function isNative(value) { var type = typeof value; return type == 'function' // Use `Function#toString` to bypass the value's own `toString` method // and avoid being faked out. ? reNative.test(fnToString.call(value)) // Fallback to a host object check because some environments will represent // things like typed arrays as DOM methods which may not conform to the // normal native pattern. : (value && type == 'object' && reHostCtor.test(toString.call(value))) || false; } // export however you want module.exports = isNative; }()); // Usage isNative(alert); // true isNative(myCustomFunction); // false
這個(gè)方法雖然不是那么的簡潔,但還是可以完成任務(wù)的!
用JavaScript創(chuàng)建新的CSS規(guī)則 insertRule
有時(shí)候我們會(huì)使用一個(gè)CSS選擇器(比如 document.querySelectorAll)來獲取一個(gè) NodeList ,然后給它們每個(gè)依次修改樣式。其實(shí)這并不是一種高效的做法,高效的做法是用JavaScript新建一段CSS樣式規(guī)則:
// Build a better Sheet object Sheet = (function() { // Build style var style = document.createElement('style'); style.setAttribute('media', 'screen'); style.appendChild(document.createTextNode('')); document.head.appendChild(style); // Build and return a single function return function(rule){ style.sheet.insertRule( rule, style.sheet.cssRules.length ); } ; })(); // Then call as a function Sheet(".stats { position: relative ; top: 0px }") ;
這些做法的效率非常高,在一些場景中,比如使用ajax新加載一段html時(shí),使用上面這個(gè)方法,你不需要操作新加載的html內(nèi)容。
判斷網(wǎng)頁元素是否具有某種屬性和樣式 matchesSelector
function matchesSelector(el, selector) { var p = Element.prototype; var f = p.matches || p.webkitMatchesSelector || p.mozMatchesSelector || p.msMatchesSelector || function(s) { return [].indexOf.call(document.querySelectorAll(s), this) !== -1; }; return f.call(el, selector); } // Usage matchesSelector(document.getElementById('myDiv'), 'div.someSelector[some-attribute=true]')
就是這7個(gè)JavaScript函數(shù),每個(gè)Web程序員都應(yīng)該知道怎么用它們。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- js 字符串操作函數(shù)
- javascript 手機(jī)號碼正則表達(dá)式驗(yàn)證函數(shù)
- Javascript Math ceil()、floor()、round()三個(gè)函數(shù)的區(qū)別
- js 格式化時(shí)間日期函數(shù)小結(jié)
- js function定義函數(shù)使用心得
- js 小數(shù)取整的函數(shù)
- js中匿名函數(shù)的N種寫法
- js正則函數(shù)match、exec、test、search、replace、split使用介紹集合
- js中字符替換函數(shù)String.replace()使用技巧
- js中通過split函數(shù)分割字符串成數(shù)組小例子
相關(guān)文章
微信小程序開發(fā)實(shí)現(xiàn)的選項(xiàng)卡(窗口頂部/底部TabBar)頁面切換功能圖文詳解
這篇文章主要介紹了微信小程序開發(fā)實(shí)現(xiàn)的選項(xiàng)卡(窗口頂部/底部TabBar)頁面切換功能,結(jié)合圖文與實(shí)例形式詳細(xì)分析了微信小程序選項(xiàng)卡切換相關(guān)操作實(shí)現(xiàn)技巧,需要的朋友可以參考下2019-05-05Nuxt.js 數(shù)據(jù)雙向綁定的實(shí)現(xiàn)
這篇文章主要介紹了Nuxt.js 數(shù)據(jù)雙向綁定的實(shí)現(xiàn),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-02-02JS實(shí)現(xiàn)的拋物線運(yùn)動(dòng)效果示例
這篇文章主要介紹了JS實(shí)現(xiàn)的拋物線運(yùn)動(dòng)效果,結(jié)合實(shí)例形式分析了javascript拋物線運(yùn)動(dòng)的相關(guān)運(yùn)算與元素動(dòng)態(tài)操作實(shí)現(xiàn)技巧,需要的朋友可以參考下2018-01-01javascript Promise簡單學(xué)習(xí)使用方法小結(jié)
下面小編就為大家?guī)硪黄猨avascript Promise簡單學(xué)習(xí)使用方法小結(jié)。小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-05-05用javascript刪除當(dāng)前行,添加行(示例代碼)
這篇文章主要介紹了用javascript刪除當(dāng)前行,添加行的示例代碼。需要的朋友可以過來參考下,希望對大家有所幫助2013-11-11