WEB开发者必备的7个JavaScript函数
2016-03-03 11:15:35 | 来源:玩转帮会 | 投稿:佚名 | 编辑:dations

原标题:WEB开发者必备的7个JavaScript函数

  我记得数年前,只要我们编写JavaScript,都必须用到几个常用的函数,比如,addEventListener 和 attachEvent,并不是为了很超前的技术和功能,只是一些基本的任务,原因是各种浏览器之间的差异造成的。时间过去了这么久,技术在不断的进步,仍然有一些JavaScript函数是几乎所有Web程序员必备的,或为了性能,或为了功能。

 防止高频调用的debounce函数

  这个 debounce 函数对于那些执行事件驱动的任务来说是必不可少的提高性能的函数。如果你在使用scroll, resize, key*等事件触发执行任务时不使用降频函数,也行你就犯了重大的错误。下面这个降频函数 debounce 能让你的代码变的高效:

// 返回一个函数,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 函数在给定的时间间隔内只允许你提供的回调函数执行一次,以此降低它的执行频率。当遇到高频触发的事件时,这样的限制显得尤为重要。

 设定时间/频率循环检测函数

  上面提到的 debounce 函数是借助于某个事件的触发。但有时候并没有这样的事件可用,那我们只能自己写一个函数来每隔一段时间检查一次。

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)
}
 禁止重复调用、只允许执行一次的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

  获取链接的绝对地址并不像你想象的那么简单。下面就是一个非常实用的函数,能根据你输入的相对地址,获取绝对地址:

var getAbsoluteUrl = (function() {
	var a;
	return function(url) {
		if(!a) a = document.createElement('a');
		a.href = url;
		return a.href;
	};
})();
// Usage
getAbsoluteUrl('/something'); // http://www.webhek.com/something

  这里使用了 a 标签 href 来生成完整的绝对URL,十分的可靠。

 判断一个JavaScript函数是否是系统原生函数 isNative

  很多第三方js脚本都会在全局变量里引入新的函数,有些甚至会覆盖掉系统的原生函数,下面这个方法就是来检查是不是原生函数的:

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

  这个方法虽然不是那么的简洁,但还是可以完成任务的!

 用JavaScript创建新的CSS规则 insertRule

  有时候我们会使用一个CSS选择器(比如 document.querySelectorAll)来获取一个 NodeList ,然后给它们每个依次修改样式。其实这并不是一种高效的做法,高效的做法是用JavaScript新建一段CSS样式规则:

// 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时,使用上面这个方法,你不需要操作新加载的html内容。

 判断网页元素是否具有某种属性和样式 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'), 'p.someSelector[some-attribute=true]')

  就是这7个JavaScript函数,每个Web程序员都应该知道怎么用它们。你可以在评论里写出其它你认为必备的函数,分享出来,谢谢。

tags:

上一篇  下一篇

相关:

想换吉米巴特勒 塞尔提克没诚意

《波士顿先驱报》今天爆料,先前交易截止日期间,塞尔提克一直想找1名顶级球星加盟,其中找寻公牛明星后卫吉

悔不当初!灰狼放弃选到柯瑞契机

看到勇士明星后卫柯瑞本季杀翻天的超级球星演出,內心感到最懊悔的球队当属灰狼,因为在2009年选秀会上,灰

女神节到了 展现性感的时候到了


如今的3月8日,已经不叫妇女节了, 而是叫做女神节。姑娘们都为自己的节日准备好了吗?当然有些姑娘

服装招商旺季:COOZIC-珂妮卡诚邀你的加盟


走进三月之后,就已经步入了一个招商旺季。作为品牌企业来说,一定早早就为这个招商旺季制定了一系

夏日预热 2016新款夏装连衣裙抢先看


虽然现在离夏日还很遥远,但是作为一个爱美的女孩子,当然要提前把握夏日流行趋势,才能在夏日来临

今年Google I/O将在3月8日开放注册

图片来源: Google 每年爆满的Google I/O, 今年初宣布在5月18到20日于加州山景市(Mountain View)的海岸线

三月女孩应该穿什么外套 杰米兰帝2016新款童装


三月,日光渐渐暖和起来,空气中弥漫着一种春天的气息。春捂秋冻,温度升高,但是妈妈们更应该懂的

兰恩2016春夏新品 选兰恩就对了


这周的气温,让我们明显感受到了春天的到来。大家都都纷纷脱去了厚重的外套,变得更加轻盈起来。春

热烈庆祝betu百图陕西甘泉店隆重开业


阳春三月,暖暖哒的阳光,照射在我们身上可谓是舒适极了。在我们享受三月舒适的时候,也需要在这个

10天苹果减肥法 让苹果助你一臂之力

  通过吃苹果来减肥的方法有很多种,有三天苹果减肥法,也有10天苹果减肥法,今天要讲的是

站长推荐: