Read JavaScript Advanced Programming 16-several functions tips

Source: Internet
Author: User

Content Summary

    • Scope-Safe constructors
    • Lazy Load function
    • function bindings
    • function throttling

one, scope-safe constructors

We know that when the constructor is called with the new operator, this inside of the constructor points to the instance of the newly created object.

function Person (name) {this. name=name;} var p=New person (' Peter '); Console.log (p.name); // results: Perter

However, if the new operator is not used and the constructor is called as a normal function, this points to the Window object.

var p1=person (' Peter '); Console.log (p1.name); // error Console.log (window.name); // Peter

Therefore, in the constructor, you should first check if this is the correct type instance, which is the scope-safe constructor.

function Person (name) {if (thisinstanceof 
Person ) { this. Name = name;} Else { return new
Person (name);  }} var New Person (' Peter '//pertervar p1 = person (' Peter '//  Perter// error

Based on this constructor, the implementation of the prototype chain is as follows:

 function   person (name) { if  (this  instanceof   person) { this . Name = name;  else   { return  new   person (name); }}  function   Student (Name,sno) {  Person.call ( this  ,name);  this . Sno=SNO;}  student.prototype    
=new
Person (); var s=New Student (' Peter ', ' N0015 '); Console.log (s.name);

The scope-safe constructors ensure that the constructor is called in the correct execution environment when the new operator is missing.

Second, lazy loading function

Some functions contain many branches, and each time it is called, the If branch is judged, but in fact it is possible to walk the same branch each time. Look at this method of creating a Cors object:

functionCreatecorsrequest (method,url) {//Create a Xhr object        varXHR =NewXMLHttpRequest (); //Start Request        if("Withcredentials"inchxhr) {Xhr.open (Method,url,true); }Else if(typeofxdomainrequest!= ' undefined ') {XHR=Newxdomainrequest ();                  Xhr.open (Method,url); }Else{XHR=NULL; }                         returnXHR; }varXHR1 = createcorsrequest (' Get ', ' http://www.othersite.com/weather.ashx ');varXHR2 = createcorsrequest (' Get ', ' http://www.othersite.com/articles.ashx ');

In fact, the same browser executes the same branch every time the object is created, so if judgment is superfluous each time, using the lazy load function can implement the function execution branch only once. There are two common scenarios:

Scenario One: When the function is called for the first time, the function is replaced with another function that executes in the appropriate way, based on the branching result. We improved the above function as follows:

functioncreatecorsrequest (method, url) {varXhr0 =NewXMLHttpRequest (); if(' Withcredentials 'inchxhr0) {    varXHR =NewXMLHttpRequest ();createcorsrequest= function  (method, url) {Xhr.open (method, URL,true); returnXHR; }  } Else if(typeofXdomainrequest! = ' undefined ') {createcorsrequest = function (method, url) {      varXHR =NewXMLHttpRequest (); XHR=Newxdomainrequest ();      Xhr.open (method, URL); returnXHR; }  } Else{createcorsrequest = function (method, url) {      return NULL; }  }  returncreatecorsrequest (method, url);}

With this improvement, you do not have to perform multiple if branch judgments on each execution, but instead simply perform the replacement succinct function. It will only have some performance penalty for the first call.

Scenario two: When declaring a function, specify the appropriate function. Also improve the above example:

 var createcorsrequest= (function (method, url) {  varXhr0 =NewXMLHttpRequest (); if(' Withcredentials 'inchxhr0) { return function  (method, url) {varXHR =NewXMLHttpRequest (); Xhr.open (method, URL,true); returnXHR; }  } Else if(typeofXdomainrequest! = ' undefined ') { return function  (method, url) {varXHR =NewXMLHttpRequest (); XHR=Newxdomainrequest ();      Xhr.open (method, URL); returnXHR; }  } Else { return function  (method, url) {return NULL; }  }})();

This scenario differs from declaring a function with Var and specifying an anonymous and automatically executed function for each branch. In this way, the function that executes the branch is determined the first time it is loaded.

Third, function binding

When executing a callback function or event handler, it is often necessary to pass the function as a variable, at which point we need to save the Code execution environment for the function. A function binding is to create a function that can invoke another function in a specific this environment with the specified parameters

var demo = {  ' Hello World ',  function  () {    Console.log (  this. message);}  } var obj = document.getElementById (' my-btn 'click ', demo.show); // Click the button results undefined

In fact, we can use closures to fix this problem:

Eventutil.addhandler (obj, ' click ',function  (event) {  demo.show ();});

But with too many closures it looks like the code is not concise enough. In many JS libraries, the bind () function is defined to implement the function binding.

function bind (FN, context) {  returnfunction  () {    return  fn.apply ( context, arguments);}  }

This bind function is relatively simple to implement, two parameters are the function and function execution environment to call, the execution result returns a function that calls the function in the specified execution environment, it passes all the arguments parameters of its intrinsic function. The calling method is as follows:

Eventutil.addhandler (obj, ' click ', bind (Demo.show,demo));
Four, function throttling

For code that executes periodically, a function throttle should be performed.

For example, the following scrolling event:

function () {       throttle (Demo,window);       }

When the page scrolls, it will continue to output the results. This high frequency response, if the method is more complex, will consume more performance. For this scenario, we can do the following optimizations:

// setting and eliminating Timers function Throttle (Method,context) {     cleartimeout (method.id);     method.id  =settimeout (function() {          Method.call (context)          },+);     } function Demo () {     console.log (1);     }   function () {       throttle (Demo,window);       }

The throttle method has two parameters: the method and scope to be executed. The timer is created the first time it is called, and subsequent calls are made by eliminating the existing timer and recreating the timer. This way, only 100ms after the last call will add the appropriate method to the execution queue.

Read JavaScript Advanced Programming 16-several functions tips

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.