Deep understanding of JavaScript Series: function mode (next) _ Basics

Source: Internet
Author: User
Tags hasownproperty

Introduced

Some of the patterns we describe in this article are called initialization mode and performance mode, mainly used in initialization and performance improvement, some of the patterns mentioned before, here is just a summary.

Functions to be executed immediately

In the 4th "Call function expression" In this series, we've described a similar function in detail, and here's a summary of just two more simple examples.

Copy Code code as follows:

Execute the function immediately after the function is declared
(function () {
Console.log (' watch out! ');
} ());

The function declared in this way can also be executed immediately
!function () {
Console.log (' watch out! ');
} ();

You can do the following.
~function () {/* * Code/} ();
-function () {/* * Code/} ();
+function () {/* * Code/} ();


object initialization for immediate execution

This pattern means that when declaring an object (rather than a function), it executes one of the methods in the object immediately to initialize the work, which can often be used on a one-time-executed code.

Copy Code code as follows:

({
Here you can define constants, set other values
maxwidth:600,
maxheight:400,

Of course, you can define the utility method
Gimmemax:function () {
return this.maxwidth + "x" + this.maxheight;
},

Class
Init:function () {
Console.log (This.gimmemax ());
More code ...
}
). Init (); So we start initializing.

Branch initialization

Branching initialization is the initialization of different code based on different conditions (scenarios), which is called conditional statement assignment. Before we do event processing, we usually use code similar to the following:

Copy Code code as follows:

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) {
}
};

Let's improve, first we have to define two interfaces, one to add event handle, one to remove event handle, the code is as follows:

Copy Code code as follows:

var utils = {
Addlistener:null,
Removelistener:null
};

The implementation code is as follows:
Copy Code code 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 much more elegant.

Self-declaring function

Typically, within a function, rewrite the same function code, such as:

Copy Code code as follows:

var scareme = function () {
Alert ("Boo!");
Scareme = function () {
Alert ("Double boo!");
};
};

This code, very easy to confuse, let's take a look at the implementation of the example results:
Copy Code code as follows:

1. Add new Attribute
Scareme.property = "properly";
2. Scareme assigns a new value to the
var prank = Scareme;
3. Call as a method
var spooky = {
Boo:scareme
};
Called using the new variable name
Prank (); "Boo!"
Prank (); "Boo!"
Console.log (Prank.property); "Properly"
Using methods to invoke
Spooky.boo (); "Boo!"
Spooky.boo (); "Boo!"
Console.log (Spooky.boo.property); "Properly"

By executing the result, you can find that the function assigned to the new variable (or internal method) does not execute the overloaded Scareme code, and the following example is the exact opposite:
Copy Code code as follows:

Using a self-declaring function
Scareme (); Double boo!
Scareme (); Double boo!
Console.log (Scareme.property); Undefined

You have to be very careful when you use this mode, otherwise the actual result is likely to be different from what you expect, but you can also use this special to do some special things.

Memory optimization

This pattern is mainly to avoid a large number of repetitive computations by using the attribute properties of functions. The usual code forms are as follows:

Copy Code code as follows:

var myFunc = function (param) {
if (!myfunc.cache[param]) {
var result = {};
// ... Complex operation ...
Myfunc.cache[param] = result;
}
return Myfunc.cache[param];
};

Cache storage
Myfunc.cache = {};


But the above code has a problem, if the incoming parameter is ToString or other similar object has some common methods, there will be problems, this time need to use the legendary hasOwnProperty method, the code is as follows:
Copy Code code as follows:

var myFunc = function (param) {
if (!myfunc.cache.hasownproperty (param)) {
var result = {};
// ... Complex operation ...
Myfunc.cache[param] = result;
}
return Myfunc.cache[param];
};

Cache storage
Myfunc.cache = {};


Or if you pass in more than one parameter, you can store these parameters by producing a CacheKey value via the JSON Stringify method, which is as follows:
Copy Code code as follows:

var myFunc = function () {
var cachekey = json.stringify (Array.prototype.slice.call (arguments)),
Result
if (!myfunc.cache[cachekey]) {
result = {};
// ... Complex operation ...
Myfunc.cache[cachekey] = result;
}
return Myfunc.cache[cachekey];
};

Cache storage
Myfunc.cache = {};


or multiple parameters, you can also use the Arguments.callee feature:
Copy Code code as follows:

var myFunc = function (param) {
var f = Arguments.callee,
Result
if (!f.cache[param]) {
result = {};
// ... Complex operation ...
F.cache[param] = result;
}
return F.cache[param];
};

Cache storage
Myfunc.cache = {};

Summarize

You don't have to sum up, everyone carefully read the code on the line

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.