Let's talk about the closure and constructor. Then let's take a look at the Deferred implemented by the closure and the deferred constructor.

Source: Internet
Author: User

Let's talk about the closure and constructor. Then let's take a look at the Deferred implemented by the closure and the deferred constructor.

As we all know, there are two ways to get an object: constructor and closure. The two methods have their own advantages and use different scenarios, but from the perspective of appearance, there is a striking difference: the object created by the closure does not need to use new. Let's take a look at the specific differences between the two:

Constructor:

Advantages:

1. easy to understand

2. inheritance can be implemented

3. The same memory used in the prototype method

Disadvantages:

1. If no special processing is performed, the new operator must be used.

2. Private attributes cannot be implemented, and all attributes will be exposed to the object.

Closure:

Advantages:

1. You do not need to use the new operator.

2. You can use the scope to do a lot of things.

3. attributes that do not want to be viewed externally can be encapsulated inside the closure.

Disadvantages:

1. Hard to understand

2. It is difficult to implement inheritance.

3. You cannot use apply and call because they are implemented using scopes.

It's boring. Let's take an example first:

Constructor method:

function Person(name,age){  this.name=name;  this.age=age;}Person.prototype.sayName=function(){  alert(this.name);}

Closure Method

function createPerson(name,age){    return {      sayName:function(){        alert(name);      }      getAge:function(){        return age;      }    }}

In jquery, both the deferred object and jqXHR adopt the closure method, while the main constructor and Event object adopt the constructor method.

Let's talk about the deferrd object first. Let's first look at how to use it. The most important thing to mention is the pipe method of jq. Of course, it will be changed to the then method later. As the source code is 1.7.1, it is called the pipe method. This method is the essence of deferred.

 var defer1=$.Deferred(); defer1 .pipe(function(arg){ var defer=$.Deferred(); setTimeout(function(){ console.log(arg++); defer.resolve(arg); },1000); return defer; }) .pipe(function(arg){ var defer=$.Deferred(); setTimeout(function(){ console.log(arg++); defer.resolve(arg); },1000); return defer; }) .pipe(function(arg){ console.log(arg); return arg; }) .pipe(function(arg){ console.log(arg); }); defer1.resolve(1);
Result:


After the browser is opened: 1 s, 1 second, and 2 3 3

For single-threaded js, it is very important to learn asynchronous programming, and here we also use the responsibility chain mode to make the structure clearer. I will not go into details about how deferred is implemented as a whole, let's look at how the pipe method is implemented.

Pipe: function (fnDone, fnFail, fnProgress) {return jQuery. deferred (function (newDefer) {jQuery. each ({done: [fnDone, "resolve"], fail: [fnFail, "reject"], progress: [fnProgress, "Y"]}, function (handler, data) {var fn = data [0], action = data [1], returned; if (jQuery. isFunction (fn) {deferred [handler] (function () {// Add the callback function returned = fn for deferred. apply (this, arguments); if (retur Ned & jQuery. isFunction (returned. promise) {returned. promise (). then (newDefer. resolve, newDefer. reject, newDefer. required y);} else {newDefer [action + "With"] (this = deferred? NewDefer: this, [returned]) ;}} else {deferred [handler] (newDefer [action]); // Add a failed callback function for deferred, the function is defer execution }});}). promise ();}

First, from the second line, every time the pipe method is executed, another deferred object is returned, and each deferred object is nothing more than two methods. One is to add a method to it, the second is the method in execution. You can think of it as similar to custom events, except that the deferred object is based on CallBacks (callback function list) and has more powerful functions, however, the principles are similar to those of custom events, all of which are based on the publish-subscribe mode. With this concept, let's look at it later.

In jQuery. deferred is used to input a function. deferred finally executes this function and passes in the deferred object parameter. The execution environment will also be changed to the deferred object, but do not forget that it is still in the function body of the first deferred object, that is, this function can access both the first deferred object and the new deferred object.


Then let's leave the each blank and look at the second parameter of each. The hanlder is "done", "fail", "progress", and the data is the corresponding array. Then let's look down, fn is the function passed in When pipe is called, and action is the corresponding execution method name. You can think of it as the fire in a custom event, so that all functions can be executed, there are only three custom events. Returned is the execution result of the function passed in by pipe.


The following uses done as an example:


Then let's look at the sentence deferred [handler] (function () {}).

Here, deferred is the first deferred object, and the callback function is added to the first deferred object. That is, when the asynchronous Queue (deferred) resolve is executed, the code in the function will be executed. What is the execution?


Returned = fn. apply (this, arguments );

This statement is to execute the passed function once, And this depends on the execution environment when the first derferred is triggered, arguments is the real parameter passed when the first deferred is triggered.


If (returned & jQuery. isFunction (returned. promise )){
Returned. promise (). then (newDefer. resolve, newDefer. reject, newDefer. Policy );
}

If the returned value has the promise method, it indicates that it is a deferred object or promise object. The promise object is the deferred object that removes the execution method, which is similar to the deferred object because the returned results are generally self-executed, it does not need to be executed externally.

First, convert the returned value to the promise object, and then put the execution method of the second deferred object into the list of functions that return the promise object. It may be a bit dizzy, so you can draw a picture to explain.


Currently, three deferred objects are involved. The execution of the first deferred object will lead to the execution of the second function that is passed in. If the return value of this function is deferred, the execution method of the second deferred object will be taken, that is, put the resolve and other methods in the third deferred function list, that is, the execution of the third deferred will lead to the execution of the second deferred, and the execution time of the second deferred is self-controlled. In this way, asynchronous queues are implemented.


When the returned value is not deferred, the second deferred object is executed directly and the parameter is the return value.


Here, we use the scope chain to give it the reference of the first deferred, and use the form parameter and apply to give it the reference of the second deferred, so that when we return a deferred, it is very clever to effectively link three deferred objects to form an asynchronous mode of responsibility chain. Here we make full use of the closure method to create objects. If we use the constructor method, we need to store the first and second deferred variables and then operate each deferred object, although it can also be implemented, it may not be so clever.

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.