[譯] 7 個基礎 JavaScript 函數

原文連接:7 Essential JavaScript Functions,by David Walshjavascript

譯者:翻譯過程當中,對於原文的敘述作了部分修改。java

debounce

防抖函數英文名叫「debounce function」,它一般是做爲頻發事件的回調使用的。對於 scrollresizekey* 這類事件,若是不使用防抖函數處理,那麼因爲事件的頻繁發生,觸發回調邏輯的不斷調用,極可能會發生性能問題。web

下面提供了防抖函數一個參考實現 debounce瀏覽器

// 返回一個函數,若是該函數被連續調用,那麼這個過程當中不會觸發 func 的調用。
// func 只會在連續調用暫停 N ms 後才被調用
// 若是參數 immediate 的值爲 true,則回調 func 是在連續調用開始時就被調用(leading edge),
// 而不是等到連續調用暫停後的 N ms(trailing edge)
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);
	};
};

// 使用
var myEfficientFn = debounce(function() {
	// 處理邏輯
}, 250);
window.addEventListener('resize', myEfficientFn);
複製代碼

上面的回調函數通過 debounce 函數包裝後,就能保證在指定的等待時間內(對應這裏的 250ms),只會觸發一次。這就能有效緩解程序的性能問題了。app

poll

下面實現了一個輪訓函數。這裏的實現邏輯是:除非 fn 的調用返回真,不然每隔 interval ms 就再調用一次 fn,直到結果爲真爲止,而後返回結果;若是調用時間過長,或調用出錯,就報錯返回。函數

// 輪訓函數
function poll(fn, timeout, interval) {
    var endTime = Number(new Date()) + (timeout || 2000);
    interval = interval || 100;

    var checkCondition = function(resolve, reject) {
        // 若是條件知足,就返回結果
        var result = fn();
        if(result) {
            resolve(result);
        }
      	// 若是條件不知足,且沒有超時,就等待 interval ms 後再繼續檢查一遍
        else if (Number(new Date()) < endTime) {
            setTimeout(checkCondition, interval, resolve, reject);
        }
        // 調用時間過長,或調用出錯,就報錯返回
        else {
            reject(new Error('timed out for ' + fn + ': ' + arguments));
        }
    };

    return new Promise(checkCondition);
}

// 使用:輪訓,確保元素爲可見時,再進行後續邏輯處理
poll(function() {
	return document.getElementById('lightbox').offsetWidth > 0;
}, 2000, 150).then(function(data) {
    // 完成輪訓,處理返回的數據
}).catch(function(err) {
    // 超時出錯,處理錯誤
});
複製代碼

輪訓在 Web 上一直頗有用,未來也是同樣。工具

once

有時候,咱們但願某個函數只調用一次,就像使用 onload 事件同樣。下面的代碼提供這個功能:性能

function once(fn, context) { 
	var result;

	return function() { 
		if(fn) {
			result = fn.apply(context || this, arguments);
			fn = null;
		}

		return result;
	};
}

// 使用
var canOnlyFireOnce = once(function() {
	return 'Fired!';
});

canOnlyFireOnce(); // "Fired!"
canOnlyFireOnce(); // "Fired!"
複製代碼

once 函數確保給定函數只會調用一次,避免了函數的重複初始化。ui

getAbsoluteUrl

由給定的一個字符串獲取絕對 URL 並不像咱們想象的那麼容易。瀏覽器提供了一個 URL 構造函數,可是若是不能提供所需的參數(有時確實提供不了),使用它就會出現問題。這裏有一個得到絕對 URL 和字符串輸入的小技巧:this

var getAbsoluteUrl = (function() {
	var a;

	return function(url) {
		if(!a) a = document.createElement('a');
		a.href = url;

		return a.href;
	};
})();

// 使用
getAbsoluteUrl('/something'); // https://davidwalsh.name/something
複製代碼

函數內部保持一個連接元素,把輸入的數據直接賦值給 href 屬性,讀取 href 屬性時就拿到絕對地址了。

譯註:這裏用到了一個知識點,就是讀取連接元素的 href 屬性時,獲得老是絕對路徑。

isNative

下面的函數 isNative 用來檢查一個函數是由瀏覽器原生提供的,還有由第三方建立的。

;(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;
}());

// 使用
isNative(alert); // true
isNative(myCustomFunction); // false
複製代碼

這個函數寫得並不漂亮,但它確實能完成任務!

insertRule

咱們能夠經過一個選擇器得到一個 NodeList(好比經過 document.querySelectorAll),並給每一個元素賦予樣式,但更有效率的方式是直接設置選擇器樣式(像咱們在樣式表中的作的那樣):

var sheet = (function() {
	// 建立 <style> 標籤
	var style = document.createElement('style');

	// 根據你的需求,還能夠添加 media (和/或 media query)
	// style.setAttribute('media', 'screen')
	// style.setAttribute('media', 'only screen and (max-width : 1024px)')

	// WebKit hack :(
	style.appendChild(document.createTextNode(''));

	// 將 <style> 元素添加到頁面
	document.head.appendChild(style);

	return style.sheet;
})();

// 使用
sheet.insertRule("header { float: left; opacity: 0.8; }", 1)
複製代碼

matchesSelector

咱們常常有驗證輸入數據的需求。要保證輸入的是個真值,或者保證表單裏的輸入數據是有效的等一些狀況。只有在這些數據驗證經過了,才能進一步進行下一步的操做。可是,咱們又是怎樣驗證一個 DOM 元素是不是有效的呢?

下面提供的 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);
}

// 使用
matchesSelector(document.getElementById('myDiv'), 'div.someSelector[some-attribute=true]')
複製代碼

在我看來,這七個 JavaScript 函數是每一個開發者都應該保存在本身的工具箱裏的。若是有什麼遺漏,歡迎你們在評論區留言分享!

(正文完)


廣告時間(長期有效)

我有一位好朋友開了一間貓舍,在此幫她宣傳一下。如今貓舍裏養的都是布偶貓。若是你也是個愛貓人士而且有須要的話,不妨掃一掃她的【閒魚】二維碼。不買也沒關係,看看也行。

(完)

相關文章
相關標籤/搜索