Interpretation of underscore.js source code: common type judgments and some useful tools and methods

Why underscore

Recently I started to look at the source code of underscore.js and put the interpretation of the source code of underscore.js in my 2016 plan.

Reading the source code of some famous framework libraries is like talking to a master, you will learn a lot. Why is underscore? The main reason is that underscore is short and concise (about 1.5k lines), encapsulating more than 100 useful methods, low coupling, very suitable for reading method by method, suitable for JavaScript beginners like the original poster. From it, you can not only learn some tricks such as using void 0 instead of undefined to avoid undefined being rewritten, but also common methods such as variable type judgment, function throttling & function debounce, and many browser compatibility. The hack, you can also learn the author's overall design ideas and the principles of API design (backward compatibility).

Later, the host will write a series of articles to share with you the knowledge learned in source code reading.

Welcome to watch~ (If you are interested, welcome star & watch~) Your attention is the motivation for the host to continue writing

Type judgment

In the first article, I briefly talked about why underscore.js uses void 0 instead of undefined. I unexpectedly received a good response. Some friends privately wrote me that I didn’t know this before, and some people urged me to continue. An interpretation article. Today I will talk to you about some commonly used JavaScript type checking methods in underscore.js, as well as some tool judgment methods.

Let’s first talk about the old-fashioned question, the judgment method of array type in JavaScript. In fact, I have analyzed the advantages and disadvantages of various judgment methods in detail in the article Judging the correct posture of array in Javascript, and gave the correct judgment code. :


function isArray(a) {

  Array.isArray ? Array.isArray(a) : Object.prototype.toString.call(a) === '[object Array]';

}

And underscore actually does exactly this:


// Is a given value an array?

// Delegates to ECMA5's native Array.isArray

// 判断是否为数组

_.isArray = nativeIsArray || function(obj) {

  return toString.call(obj) === '[object Array]';

};

nativeIsArray is the Array.isArray method in ES5, if it is supported, it will be called first; and the toString variable saves Object.prototype.toString.

How to judge the object? Underscore counts variables of type function and object as objects, of course null must be removed.


// Is a given variable an object?

// 判断是否为对象

// 这里的对象包括 function 和 object

_.isObject = function(obj) {

  var type = typeof obj;

  return type === 'function' || type === 'object' & !!obj;

};

Look at'Arguments','Function','String','Number','Date','RegExp','Error' these types of judgments, in fact, you can use Object.prototype.toString.call to judge, so write Together:


// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.

// 其他类型判断

_.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {

  _['is' + name] = function(obj) {

    return toString.call(obj) === '[object ' + name + ']';

  };

});

But look at the isArguments method, in IE


// Define a fallback version of the method in browsers (ahem, IE

// there isn't any inspectable "Arguments" type.

// _.isArguments 方法在 IE

// IE

// 结果是 [object Object]

// 而并非我们期望的 [object Arguments]。

// so 用是否含有 callee 属性来判断

if (!_.isArguments(arguments)) {

  _.isArguments = function(obj) {

    return _.has(obj, 'callee');

  };

}

Tool category judgment method

Next, let's look at some commonly used tool judgment methods.

Determining whether an element is a DOM element is very simple, just make sure it is not empty and the nodeType attribute is 1:


// Is a given value a DOM element?

// 判断是否为 DOM 元素

_.isElement = function(obj) {

  // 确保 obj 不是 null

  // 并且 obj.nodeType === 1

  return !!(obj & obj.nodeType === 1);

};

How to judge an element as NaN? NaN actually belongs to the Number type. Object.prototype.toString.call(NaN) returns "[object Number]", and NaN is not equal to itself. You can use these two points to make a judgment:


// Is the given value `NaN`? (NaN is the only number which does not equal itself).

// 判断是否是 NaN

// NaN 是唯一的一个 `自己不等于自己` 的 number 类型

_.isNaN = function(obj) {

  return _.isNumber(obj) & obj !== +obj;

};

Of course, underscore has many other useful tool judgment methods. For details, please refer to the source code https://github.com/hanzichi/underscore-analysis/blob/master/underscore-1.8.3.js/src/underscore-1.8 .3.js#L1192-L1263 this part.

If you think what I have shared is helpful to you, please follow my Repo https://github.com/hanzichi/underscore-analysis

Guess you like

Origin blog.51cto.com/15080022/2588315