Java programmer's JavaScript learning notes (9 -- jQuery tool method)

Source: Internet
Author: User

Java programmer's JavaScript learning notes (9 -- jQuery tool method)

We plan to complete this note in the following order:

1. concept.
2. Copy and inherit attributes.
3. this/call/apply.
4. Closure/getter/setter.
5. prototype.
6. object-oriented simulation.
7. Basic jQuery mechanism.
8. jQuery selector.
9. jQuery tool method.
10. jQuery-extension at the class level.
11. jQuery-extensions at the "object" level.
12. jQuery-extended selector.
13. jQuery UI.
14. Extend the jQuery UI.

This is Part 1 of the notes. From the perspective of jQuery source code, let's talk about jQuery's tool methods.


Author blog: http://blog.csdn.net/stationxp

Author Weibo: http://weibo.com/liuhailong2008

Reprinted with the author's consent


1. First, let's take a look at how to use the following tools and methods:

var t = $.trim('   >>_<<   ');var ps = $.param({x:15,y:16});jQuery.type(function(){}) === "function"

JQuery's tool methods are relatively independent from jQuery itself.

2. How are these methods defined?
Let's guess. Try it.
We know that jQuery ($) is a global variable. These methods should be attributes of jQuery variables.
We can use the following syntax to add:

jQuery.xx = function(a,b){ return a + b;}// tryvar r1 = jQuery.xx(2,3);console.log(r1);// output : 5var r2 = $.xx(3,3);console.log(r2);// output : 6
The code above indicates that $ and jQuery reference the same variables, they are the same.
These codes achieve the goal of defining tool methods, but does jQuery do this?

3,
View jQuery source code. jQuery defines the tool and method using the following syntax:

jQuery.extend({ noConflict: function( deep ) {  if ( window.$ === jQuery ) {window.$ = _$;  }  if ( deep && window.jQuery === jQuery ) {window.jQuery = _jQuery;  }  return jQuery; } //, ... });

The extend method is defined as follows:

// Defines a method and assigns it to jQuery. fn. extend and jQuery. extend. // jQuery. fn. extend and jQuery. although the extend definition is the same, but the caller is different, so that this in the method points to different, thus implementing different functions. // Parameters are not explicitly declared, but are dynamically obtained through arguments to support richer functions. JQuery. extend = jQuery. fn. extend = function () {var src, copyIsArray, copy, name, options, clone, // use the first parameter as the target object target = arguments [0] | {}, // I is initialized to 1, so I do not know what to do with I = 1, // length indicates the number of parameters. length = arguments. length, // deep indicates whether to perform deep copy. The default value is no. Deep = false; // Handle a deep copy situation if (typeof target = "boolean") {// if the first parameter is of the boolean type, the second parameter is the target object //, for example, jQuery. extend (false, UiObject ,...); deep = target; target = arguments [1] |{}; // I is the array subscript of the current parameter, starting from 0 I = 2 ;} // The target object can be a function or object. If other parameters are input, the target object is empty by default. If (typeof target! = "Object "&&! JQuery. isFunction (target) {target = {};}// currently, if the first parameter is not a Boolean value, the I value is 1, and the length is 1, that is, extend (obj) // if it is Boolean, the I value is 2, and the length is also 2, that is, the extend (true, obj) Case // In short, src if (length = I) {// jQuery has not passed in the passed-in parameter. // The subscript of the parameter is re-directed to the passed-in parameter, that is, src target = this; -- I;} // now I points to a parameter next to the target, which should be src //. When each parameter passed in later is src for (; I <length; I ++) {// Only deal with non-null/undefined values // This filters out non-null values. Will undefined values be filtered out? // Do not judge whether typeof src is "object" or "function? If (options = arguments [I])! = Null) {// assign a value to the variable options // Extend the base object for (name in options) {src = target [name]; copy = options [name]; // think about it: if you are already in your own family, don't get lost. // Prevent never-ending loop if (target = copy) {continue ;} // for common objects and arrays, consider recursive deep copy. // What is a common object? Isn't function counted? If (deep & copy & (jQuery. isPlainObject (copy) | (copyIsArray = jQuery. isArray (copy) {if (copyIsArray) {// set the default value of next loop copyIsArray = false; // if the target object originally has this attribute, but it is not of the array type, clone = src & jQuery. isArray (src )? Src: [];} else {// if the target object does not have this attribute or is not a common object, the default value is {}. // If a common object already exists, clone = src & jQuery. isPlainObject (src )? Src: {};}// recursive call // if it is written as jQuery. is extend (deep, clone, copy) the same? // Never move original objects, clone them target [name] = jQuery. extend (deep, clone, copy); // Don't bring in undefined values // undefined and! = Null must be further understood} else if (copy! = Undefined) {// click it. In the case of jQuery. extend ({xx, xfasf});, the extension is this, that is, the caller. // Directly modify the target, and do not create target [name] = copy ;}}// Return the modified object return target ;};

4. Let's see how jQuery. isPlainObject is defined.

IsPlainObject: function (obj) {// Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well // it must be an object. // Because of IE, we must also check whether the constructor attribute exists. // Make sure you do not miss the Dom nodes and window objects. They are not common objects. If (! Obj | jQuery. type (obj )! = "Object" | obj. nodeType | jQuery. isWindow (obj) {// The following parameters are not passed: NULL, undefined, 0, and jQuery. type Returns non-object, dom object, and window object // Therefore, if typeof is string, number, function, regular, or date, return false is not returned ;} try {// Not own constructor property must be Object if (obj. constructor &&! Core_hasOwn.call (obj, "constructor ")&&! Core_hasOwn.call (obj. constructor. prototype, "isPrototypeOf") {return false ;}} catch (e) {// IE8, 9 Will throw exceptions on certain host objects #9897 return false ;} // during enumeration, its own attributes are first enumerated. If the last attribute is its own, all attributes are its own attributes. // In short, there cannot be any inherited attribute that can be enumerated, your sister! Why is there such a requirement? // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for (key in obj) {} return key = undefined | core_hasOwn.call (obj, key );}

5,
Try it

jQuery.extend({ sayHi:function(you){  console.log('hi',you); }});$.sayHi('Stanley'); // output : hi Stanley

Not bad! What if I want to overwrite existing jQuery methods?

jQuery.extend({ isPlainObject:function(obj){return 'baby, I am not sure.'; }});var r = $.isPlainObject({});console.log(r); // output : baby, I am not sure.

This... Okay, you can do it. Think about other methods.

Play again:

jQuery.extend({ extend:function(obj){  // do nothing  return 'who am i?'; }});var r = $.extend({x:function(){ alert();}});console.log(r); // output : who am i?jQuery.x();// error : function not be defined

In this way, no one can extend the jQuery method through extend.
But there can be more direct methods.



Related Article

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.