Deep understanding of JavaScript series (50): function mode (Part 2)

Source: Internet
Author: User
Tags hasownproperty
Introduction

Some of the models we introduce in this article are called initialization mode and performance mode. They are mainly used for initialization and performance improvement. Some models have been mentioned before. Here is a summary.

Function to be executed immediately

In article 4th of this series, "function expressions for immediate calls", we have already described similar functions in detail. Here we just give two simple examples to make a summary.

 //  Execute the function immediately after the function is declared. ( Function  () {Console. Log ( 'Watch out! ' );}());  //  The declared function can also be executed immediately. ! Function  () {Console. Log ( 'Watch out! ' );}();  // You can use either of the following methods. ~ Function (){ /*  Code  */  }(); - Function (){ /*  Code  */  }(); + Function (){ /*  Code  */ }();

Initialize the object to be executed immediately

This mode means that when an object (rather than a function) is declared, a method in the object is immediately executed for initialization. Generally, this mode can be used for one-time execution.Code.

 ({  //  Here you can define constants and set other values. # Maxwidth: 600 , Maxheight: 400 ,  //  You can also define the utility method. Gimmemax: Function  (){  Return   This . Maxwidth + "X" + This . Maxheight ;},  //  Initialization Init: Function  () {Console. Log (  This  . Gimmemax ());  //  More code...   }). INIT ();  //  Initialization starts. 

Branch Initialization

Branch initialization refers to initializing different codes based on different conditions (scenarios) during initialization, that is, assigning values to conditional statements. Previously, when we were doing event processing, we usually used code similar to the following:

 VaR Utils ={Addlistener:  Function  (EL, type, FN ){  If ( Typeof Window. addeventlistener === 'function' ) {El. addeventlistener (type, FN,  False  );}  Else   If ( Typeof Document. attachevent! = 'Undefined' ) {El. attachevent ( 'On' +Type, FN );}  Else  {El [ 'On' + type] = FN ;}, removelistener:  Function  (EL, type, FN ){}}; 

First, we need to define two interfaces: one to add the event handle and the other to remove the event handle. The Code is as follows:

 
VaRUtils ={Addlistener:Null, Removelistener:Null};

The implementation code is as follows:

 If (Typeof Window. addeventlistener === 'function' ) {Utils. addlistener = Function  (EL, type, FN) {El. addeventlistener (type, FN,  False  );};}  Else   If ( Typeof Document. attachevent! = 'Undefined '){ //  IE Utils. addlistener = Function (EL, type, FN) {El. attachevent ( 'On' + Type, FN) ;}; utils. removelistener = Function  (EL, type, FN) {El. detachevent ( 'On' + Type, FN );};}  Else { //  Other old browsers Utils. addlistener = Function  (EL, type, FN) {El [ 'On' + type] = FN ;}; utils. removelistener =Function  (EL, type, FN) {El [ 'On' + type] = Null  ;};} 

Is it convenient to use it? The Code is also more elegant.

Self-declared functions

Generally, the code of a function with the same name is rewritten within the function, for example:

 
VaRScareme =Function() {Alert ("Boo! "); Scareme=Function() {Alert ("Double Boo! ");};};

This code is very confusing. Let's take a look at the execution results of the example:

 //  1. Add new attributes Scareme. Property = "properly" ;  //  2. scareme is associated with a new value.   VaR Prank = Scareme;  //  3. As a method call   VaR Spooky = {BOO: scareme };  //  Call with the new variable name Prank (); //  "Boo! " Prank (); // "Boo! " Console. Log (prank. property ); //  "Properly"  //  Call using methods Spooky. Boo (); //  "Boo! " Spooky. Boo (); //  "Boo! " Console. Log (spooky. Boo. property ); //  "Properly" 

Through the execution results, we can find that the scheduled function value is assigned to the new variable (or internal method), and the Code does not execute the overloaded code of The sceme, but the following example is exactly the opposite:

//Use self-declared functionsScareme ();//Double Boo!Scareme ();//Double Boo!Console. Log (scareme. property );//Undefined

When using this mode, you must be very careful. Otherwise, the actual results may be different from the expected results. Of course, you can also use this special method to perform some special operations.

Memory Optimization

This mode mainly uses the attribute features of the function to avoid a large number of repeated computations. The code format is as follows:

VaRMyfunc =Function(PARAM ){If(!Myfunc. cache [Param]) {VaRResult ={};//... Complex operations...Myfunc. cache [Param] =Result ;}ReturnMyfunc. cache [Param];};//Cache storageMyfunc. cache = {};

However, the above Code has a problem. If the input parameter is tostring or some other common methods similar to the object, the problem will occur. In this case, you need to use the legendaryHasownpropertyThe Code is as follows:

VaRMyfunc =Function(PARAM ){If(!Myfunc. cache. hasownproperty (PARAM )){VaRResult ={};//... Complex operations...Myfunc. cache [Param] =Result ;}ReturnMyfunc. cache [Param];};//Cache storageMyfunc. cache = {};

Alternatively, if you input multiple parameters, you can store these parameters using the JSON stringify method to produce a cachekey value. The Code is as follows:

VaRMyfunc =Function(){VaRCachekey =JSON. stringify (array. Prototype. Slice. Call (arguments), result;If(!Myfunc. cache [cachekey]) {result={};//... Complex operations...Myfunc. cache [cachekey] =Result ;}ReturnMyfunc. cache [cachekey];};//Cache storageMyfunc. cache = {};

You can also use arguments. callee for multiple parameters:

VaRMyfunc =Function(PARAM ){VaRF =Arguments. callee, result;If(!F. cache [Param]) {result={};//... Complex operations...F. cache [Param] =Result ;}ReturnF. cache [Param];};//Cache storageMyfunc. cache = {};

 



Reprinted:
Http://www.cnblogs.com/TomXu

 

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.