7个基本JavaScript函数

我记得在JavaScript的早期,您需要一个几乎所有功能的简单功能,因为浏览器供应商实现的功能有所不同,而不仅仅是边缘功能,基本功能(例如addEventListenerattachEvent 。 时代已经变了,但是每个开发人员仍然需要在其功能库中拥有一些功能,以实现易于使用的性能。

debounce

在事件推动的表演中,防反弹功能可以改变游戏规则。 如果您不使用带有scrollresizekey*事件的反跳功能,则可能是错误的。 这是一个debounce功能,可保持代码高效:

// Returns a function, 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);

debounce功能不允许在每个给定的时间范围内多次使用回调。 将回调函数分配给频繁触发的事件时,这一点尤其重要。

poll

正如我在debounce函数中提到的那样,有时您不必插入事件来表示所需的状态-如果该事件不存在,则需要定期检查所需的状态:

// The polling function
function poll(fn, timeout, interval) {
    var endTime = Number(new Date()) + (timeout || 2000);
    interval = interval || 100;

    var checkCondition = function(resolve, reject) {
        // If the condition is met, we're done! 
        var result = fn();
        if(result) {
            resolve(result);
        }
        // If the condition isn't met but the timeout hasn't elapsed, go again
        else if (Number(new Date()) < endTime) {
            setTimeout(checkCondition, interval, resolve, reject);
        }
        // Didn't match and too much time, reject!
        else {
            reject(new Error('timed out for ' + fn + ': ' + arguments));
        }
    };

    return new Promise(checkCondition);
}

// Usage:  ensure element is visible
poll(function() {
	return document.getElementById('lightbox').offsetWidth > 0;
}, 2000, 150).then(function() {
    // Polling done, now do something else!
}).catch(function() {
    // Polling timed out, handle the error!
});

长期以来,轮询在网络上一直很有用,并且在将来仍将继续!

once

有时,您希望给定功能仅发生一次,类似于您使用onload事件的方式。 这段代码为您提供了所说的功能:

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

once函数确保给定的函数只能被调用一次,从而防止重复初始化!

getAbsoluteUrl

从变量字符串获取绝对URL并不像您想的那么容易。 有URL构造函数,但是如果您不提供必需的参数(有时却不能提供),它可以起作用。 这是一个获取URL和输入字符串的绝对技巧:

var getAbsoluteUrl = (function() {
	var a;

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

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

// Usage
getAbsoluteUrl('/something'); // https://davidwalsh.name/something

“ burn”元素href为您处理和URL废话,从而提供可靠的绝对URL。

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

// Usage
isNative(alert); // true
isNative(myCustomFunction); // false

该功能不是很漂亮,但是可以完成工作!

insertRule

我们都知道我们可以从选择器中获取一个NodeList(通过document.querySelectorAll )并为它们提供样式,但是更有效的方法是将该样式设置为选择器(就像在样式表中一样):

var sheet = (function() {
	// Create the <style> tag
	var style = document.createElement('style');

	// Add a media (and/or media query) here if you'd like!
	// style.setAttribute('media', 'screen')
	// style.setAttribute('media', 'only screen and (max-width : 1024px)')

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

	// Add the <style> element to the page
	document.head.appendChild(style);

	return style.sheet;
})();

// Usage
sheet.insertRule("header { float: left; opacity: 0.8; }", 1);

在动态的AJAX繁重的网站上工作时,这尤其有用。 如果将样式设置为选择器,则无需考虑对可能与该选择器匹配的每个元素进行样式设置(现在或将来)。

matchesSelector

通常,我们会在前进之前验证输入; 确保真实值,确保表单数据有效等。但是,我们要确保元素有资格继续前进的频率是多少? 您可以使用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]')

那里有:每个开发人员都应在其工具箱中保留的七个JavaScript函数。 有我错过的功能吗? 请分享!

翻译自: https://davidwalsh.name/essential-javascript-functions

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值