Fully understand the writing and usage of Javascript closures and closures

Source: Internet
Author: User
Tags delete cache

Fully understand the writing and usage of Javascript closures and closures
I haven't written a blog for a long time, and I have become lazy after a long 11 holiday. Today I am recovering. Now, let's go to the topic. Let's talk about the closure in javascript today! This blog mainly describes some practical things, including writing, using, and using closures. I. What are the writing and usage of closures? 1. What is the closure? The official explanation of the closure is: an expression with many variables and an environment bound to these variables (usually a function), so these variables are part of the expression. Closure features: 1. As a reference to a function variable, a function is activated when it is returned. 2. A closure is a stack that does not release resources when a function returns. Simply put, Javascript allows the use of internal functions-that is, function definitions and function expressions are located in the body of another function. In addition, these internal functions can access all the local variables, parameters, and other declared internal functions declared in their external functions. When one of these internal functions is called outside the external functions that contain them, a closure is formed. 2. Write methods and usage of closures first understand that everything in JS is an object, and a function is an object. Next, let's take a look at the five writing methods of closures to briefly understand what closures are. It will be explained in detail later. Copy code // write the function Circle (r) {this. r = r;} Circle. PI = 3.14159; Circle. prototype. area = function () {return Circle. PI * this. r * this. r;} var c = new Circle (1.0); alert (c. area (); Copying code is nothing special, just adding some attributes to the function. Copy code // 2nd writing methods var Circle = function () {var obj = new Object (); obj. PI = 3.14159; obj. area = function (r) {return this. PI * r;} return obj;} var c = new Circle (); alert (c. area (1.0); copy the code to declare a variable and assign a function as a value to the variable. Copy code // 3rd writing methods var Circle = new Object (); Circle. PI = 3.14159; Circle. area = function (r) {return this. PI * r;} alert (Circle. area (1.0); copy the code. It is better to understand this method, that is, a new object, and then add attributes and methods to the object. Copy code // 4th writing methods var Circle = {"PI": 3.14159, "area": function (r) {return this. PI * r ;}}; alert (Circle. area (1.0); Copying code is more convenient. Var obj = {} is an empty object. // There are 5th writing methods: var Circle = new Function ("this. PI = 3.14159; this. area = function (r) {return r * this. PI;} "); alert (new Circle ()). area (1.0); To be honest, I have never used this method. You can refer to it. In general, the above several methods are common in 2nd and 4th. You can choose one based on your habits. The Prototype commonly used in JS is shown in the code above. What is Prototype used? Next let's take a look: copy the code var dom = function () {}; dom. show = function () {alert ("Show Message") ;}; dom. prototype. display = function () {alert ("Property Message") ;}; dom. display (); // error dom. show (); var d = new dom (); d. display (); d. show (); // error to copy the code, we first declare a variable and assign a function to it, because in Javascript, each function has a Portotype attribute, but the object does not. Add two methods, respectively add and add to break the Prototype above, to see the call situation. The analysis result is as follows: 1. The object method defined by the prototype attribute is not used. It is a static method and can only be called directly by class name! In addition, this variable cannot be used in this static method to call other properties of the object! 2. The object method defined by the prototype attribute is non-static and can only be used after instantiation! In this method, other attributes of the object can be referenced! Next let's take a look at the code: copy the code var dom = function () {var Name = "Default"; this. sex = "Boy"; this. success = function () {alert ("Success") ;};}; alert (dom. name); alert (dom. sex); let's take a look at the copied code. What will it show? The answer is Undefined. Why? This is because every function in Javascript forms a scope, and these variables are declared in the function, so they are in the scope of the function and cannot be accessed externally. To access variables, you must create a new instance. Copy the code var html = {Name: 'object', Success: function () {this. say = function () {alert ("Hello, world") ;}; alert ("Obj Success") ;}; copy the code and check this syntax, in fact, this is a "syntactic sugar" of Javascript, which is equivalent to copying the code var html = new Object (); html. name = 'object'; html. success = function () {this. say = function () {alert ("Hello, world") ;}; alert ("Obj Success"); copying the code variable html is an object, not a function, therefore, without the Prototype attribute, the methods are also public methods, and html cannot be instantiated. Otherwise, the following error occurs: but it can be assigned to other variables as values, such as var o = html; we can use it like this: alert (html. name); html. success (); speaking of this, is it all done? Careful people will ask how to access the Say method in the Success method? Is it html. Success. Say? Of course not. As mentioned above, access is not allowed due to the limitation of the scope. So use the following method to access: copy the code var s = new html. success (); s. say (); // You can also write html. success. prototype. show = function () {alert ("HaHa") ;}; var s = new html. success (); s. show (); copy the code about the Javascript scope. You can find some information online if you are interested. II. The use of Javascript closures, in fact, by using closures, we can do a lot of things. For example, it simulates the object-oriented code style. It is more elegant and concise to express the Code. In some aspects, it improves the code execution efficiency. 1. Anonymous self-execution functions we know all the variables. If the var keyword is not added, all the variables will be added to the Global Object Attributes by default, there are many disadvantages to adding such temporary variables to global objects. For example, other functions may misuse these variables, resulting in a large global object, the access speed is affected (because the value of the variable needs to be traversed from the prototype chain ). Except that variables are used with the var keyword each time, we often encounter such a situation that some functions only need to be executed once and internal variables do not need to be maintained, for example, for UI initialization, we can use the closure: copy the code var data = {table: [], tree: {}}; (function (dm) {for (var I = 0; I <dm. table. rows; I ++) {var row = dm. table. rows [I]; for (var j = 0; j <row. cells; I ++) {drawCell (I, j) ;}}) (data); copy the code and create an anonymous function and execute it immediately, because external variables cannot be referenced, resources are immediately released after the function is executed. The key is not to pollute global objects. 2. Result caching we may encounter many situations during development. Suppose we have a function object that takes a long time to process, and each call will take a long time, then we need to store the calculated value. When calling this function, we first find it in the cache. If it cannot be found, we will perform the calculation, then update the cache and return the value, if yes, you can directly return the value you have found. The closure can do this because it does not release external references, so that the internal values of the function can be retained. Copy the code var CachedSearchBox = (function () {var cache ={}, count = []; return {attachSearchBox: function (dsid) {if (dsid in cache) {// return cache [dsid] if the result is in the cache; // directly return the cached object} var fsb = new uikit. webctrl. searchBox (dsid); // create cache [dsid] = fsb; // update cache if (count. length> 100) {// the size of the cache <= 100 delete cache [count. shift ()] ;}return fsb ;}, clearSearchBox: function (dsid) {if (dsid in cache) {cache [dsid]. clear Selection () ;}};}) (); CachedSearchBox. attachSearchBox ("input"); copy the code so that the object will be read from the Cache during the second call. 3. encapsulate and copy the code var person = function () {// The variable scope is inside the function, and the outside cannot access var name = "default"; return {getName: function () {return name ;}, setName: function (newName) {name = newName ;}}(); print (person. name); // direct access, the result is undefined print (person. getName (); person. setName ("abruzzi"); print (person. getName (); the result is as follows: undefined default abruzzi copy Code 4. Implementation class and inheritance copy code function Person () {var name = "default"; return {getNa Me: function () {return name ;}, setName: function (newName) {name = newName ;}}; var p = new Person (); p. setName ("Tom"); alert (p. getName (); var Jack = function () {}; // inherited from Person Jack. prototype = new Person (); // Add the private method Jack. prototype. say = function () {alert ("Hello, my name is Jack") ;}; var j = new Jack (); j. setName ("Jack"); j. say (); alert (j. getName (); copy the code. We define Person, which is like a class. We create a Person object and access its Method. Next we define Jack, inherit the Person, and add our own method.

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.