Tool methods in jquery $.isfunction, $.isarray (), $.iswindow ()

Source: Internet
Author: User
Tags number strings

This article official address: Http://www.xiabingbao.com/javascript/2015/07/04/javascript-type

In JavaScript, we explain the principle of the implementation of jquery in the judgment of variable types $.type() . Of course, jquery offers several other tool methods in addition to the $.type tool methods available:,, $.isFunction() , $.isArray() and $.isWindow() $.isNumeric() so on. These methods can be seen from the name of the method, and here we come to one by one to explain the internal details of the methods implemented in jquery (2.1.2).

1. $.isfunction ()

$.isFunction()is used to determine if a variable is a function type, we take a few examples to see:

$.isFunction(123); // false$.isFunction(true);// false$.isFunction([1, 2]);// false$.isFunction(function(){});// truefunction func(){}var sfunc = function(){}$.isFunction(func); // true$.isFunction(sfunc);// true

As can be seen from the above example, $.isFunction(param) if the incoming Param is a function type, it returns True, and the other type returns false.

Look at the source code of jquery, which we can see, $.isFunction() is also $.type() achieved by:

isFunction: function( obj ) {    return jQuery.type(obj) === "function";}
2. $.isarray ()

$.isArray()is used to determine if a variable is of type array. Also, let's look at the usage of $.isarray in a few examples:

$.isArray(123);   // false$.isArray(true);  // false$.isArray([1, 2]);// true$.isArray(new Array(3, 4)); // true

Either the literal of the array or the variable created with the new keyword can be used to $.isArray() determine whether it is an array type. In the jquery source code, $.isarray invokes the IsArray method provided by the native array. Because in a higher version of the browser, native JavaScript has been given a isArray way to determine if the variable is of type array.

isArray: Array.isArray
3. $.iswindow ()

$.isWindow()is used to determine if the current variable is a window, such as:

$.isWindow(window); // true$.isWindow([]);    // false$.isWindow(null);  // false

In the jquery source code:

isWindow: function( obj ) {    return obj != null && obj === obj.window;}

He determines if obj is a Window object by judging if obj has a window property. Because the Window object has a property window, it is himself, so: window.window===window , the same:

window.window.window.window === window;

can continue to circulate.

And why is the code first to determine if obj is null? Because the code throws an exception when judging whether null or undefined has a window property:uncaught typeerror:cannot Read Properties ' window ' of NULL. Therefore, in order to prevent code errors, first of all to determine whether the variable is null, if NULL, it is certainly not a Window object, directly return FALSE, otherwise determine if the variable has a window property.

4. $.isnumeric ()

$.isNumeric()is used to determine whether the current variable is a numeric type, but why I do not use $.type()=="number" to judge it. Let's take a look at some official examples:

$.isNumeric("-10");  // true$.isNumeric(16);     // true$.isNumeric(0xFF);   // true$.isNumeric("0xFF"); // true$.isNumeric("8e5");  // true (exponential notation string)$.isNumeric(3.1415); // true$.isNumeric(+10);    // true$.isNumeric(0144);   // true (octal integer literal)$.isNumeric("");     // false$.isNumeric({});     // false (empty object)$.isNumeric(NaN);    // false$.isNumeric(null);   // false$.isNumeric(true);   // false$.isNumeric(Infinity); // false$.isNumeric(undefined); // false

Use a $.isNumeric() number that can determine the string type " -10", "0xFF ", and $.type() then resolve it to a string type.

In the jquery source code, this is how the variable type is judged:

isNumeric: function( obj ) {    // parseFloat NaNs numeric-cast false positives (null|true|false|"")    // ...but misinterprets leading-number strings, particularly hex literals ("0x...")    // subtraction forces infinities to NaN    // adding 1 corrects loss of precision from parseFloat (#15100)    return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0;}

First determine if its variable is an array type, and if it returns false directly. But why should we first determine if the variable is an array type? Because an array of type [123] can be subtracted directly, it can also be converted to a number by parsefloat (["123"]):

[100] - 60          // 40[100] - [60]        // 40parseFloat([123])   // 123parseFloat(["345"]) // 345

Therefore it cannot be converted directly through the parsefloat () and then judged. The first step is to determine if the variable is an array, or not to make the next decision:

(obj - parseFloat( obj ) + 1) >= 0

A pure number, a string type number, a number starting with 0 (8), an array starting with 0x (16), and so on, can be converted to a 10-digit number normally by parsefloat (). The operation of the above expression is certainly greater than 0. But why add 1? The code also explains that the conversion to the parsefloat () will result in the loss of precision, so after +1, the result of the operation is more accurate.

and other types of parsefloat () after the conversion is nan, Nan no matter what the operation, can not be compared with 0, return false.

In previous versions of jquery (such as 2.0.2):

isNumeric: function( obj ) {    return !isNaN( parseFloat(obj) ) && isFinite( obj );}

We can find that the use of such code $.isNumeric([123]) after running to get the true, and actually, it is the array type. But fortunately, the subsequent version has been repaired.

5. $.isemptyobject ()

$.isEmptyObject()is not used to determine the type of the variable, but to determine whether an object type is empty and does not contain any attributes.

Starting with JQuery 1.4, this method detects both the properties of the object itself and the attributes inherited from the prototype (hence no use of hasownproperty). The parameter should be a normal JavaScript object, and for other types of objects (DOM elements, the original Strings/numbers,host object) may not provide consistent results across browsers.

$.isEmptyObject({name:"wenzi"}) // false$.isEmptyObject({})  // truefunction Person(){    this.name = "wenzi"}$.isEmptyObject(new Person()); // falsefunction Student(){}Student.prototype.name = "wenzi";$.isEmptyObject(new Student()); // false

We can see that both the property of the object itself, or the property on the prototype, will return false as long as it exists.

isEmptyObject: function( obj ) {    var name;    for ( name in obj ) {        return false;    }    return true;}

In jquery, this is for~in done by testing. Because the for~in is also able to loop to the properties on the prototype, if it goes into the loop, it means that obj has a property, which is false, otherwise it returns true.

6. Summary

jquery also provides a variety of tools and methods, which makes it easier to write JS code. Summarize other tool methods when you have the opportunity later.

This article official address: Http://www.xiabingbao.com/javascript/2015/07/04/javascript-type

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Tool methods in jquery $.isfunction, $.isarray (), $.iswindow ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.