The role of JavaScript domain and closure -- another angle: extend your knowledg

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

The original address

-This article is a bit mean, can expand your awareness of the scope and closure.

The content of this article

I think, to try to explain the JavaScript scope and closure is very entanglements.

Background

There are a lot of articles and blogs are in scope to explain (SCOPE) and closed (closure), but overall, I think most of them are not very clear. In addition, some people think, most probably it did not actually happen, everyone has probably by other 15 kinds of language development, but in my experience, many of these people have to write JavaScript code with HTML and CSS background, rather than the C and Java.

Therefore, the objective of this paper is, let every man have what is the scope and closure, how they work, especially for how you can benefit from. After reading this article, you need to understand the basic concepts of variables and functions.

 

Scope(Scope)

A scope is a variable and a function can access where, and what is the execution environment. The most basic is, a variable or function can be defined at global or local scope. Variables have function scope of so-called, function and variable has the same scope.

The global scope (Global)

When is the global time, means, in your code, can be accessed from anywhere. As shown in the following code:

var monkey = "Gorilla";   function greetVisitor() { return alert("Hello dear blog reader!"); }

If the code is executed in the Web browser, then the function, scope is window, therefore, the operation of all things in a Web browser window, the functions are available.

Local (Local) scope

In contrast to the global scope, definition of the local scope only after you in one part of the code and access, such as a function. The code shown below:

function talkDirty() { var saying = "Oh, you little VB lover, you"; return alert(saying); } alert(saying); // Throws an error

The code above, the variable saying is only available in the talkDirty function. While outside, it is not defined. Note: if the statement saying front without the VaR keyword, then the variable will automatically become a global variable.

This also means that, if you have nested (nested) function, then, the nested function will be able to access the function contains variables and functions:

function saveName(firstName) { function capitalizeName() { return firstName.toUpperCase(); } var capitalized = capitalizeName(); return capitalized; } alert(saveName("Robert")); // Returns "ROBERT"

As seen above, the nested function capitalizeName without any parameters, parameters of firstName saveName function can access it outside. The sake of clarity, let us look at the following example:

function siblings() { var siblings = ["John", "Liza", "Peter"]; function siblingCount() { var siblingsLength = siblings.length; return siblingsLength; } function joinSiblingNames() { return "I have " + siblingCount() + " siblings:\n\n" + siblings.join("\n"); } return joinSiblingNames(); } alert(siblings()); // Outputs "I have 3 siblings: John Liza Peter"

The code above, the two nested function can access a siblings array containing the function, and, each nested function can access another nested function equally (in this case, joinSiblingNames can access the siblingCount). However, the siblingCount function in the variable siblingsLength is only available at the function where it, is also the scope.

 

Closure(Closures)

Now, when you want to get a better grasp the scope is what, let's add closure to the combination. Closure is the expression, is often a function, another a context variable settings. Or, to try and make it easier, internal function relates to a local variable to create closure. For example:

function add(x) { return function (y) { return x + y; }; } var add5 = add(5); var no8 = add5(3); alert(no8); // Returns 8

What happened.?

  1. When the add function is invoked, it returns a function.
  2. The returned function closed context, remember the parameter x in what is the time (for example, the code above 5).
  3. When calling the add function returns the result is assigned to the variable add5, the add5 function always know what is x, when the add5 is initialized to create.
  4. The add5 variable references a function, it is always the arguments passed to it and 5.
  5. This means that, when the 3 call to add5, it should return 3 plus 5, equal to 8.

Therefore, in the JavaScript world, in fact, the actual add5 function as shown below:

function add5(y) { return 5 + y; }

The circulation problem of the notorious repute

How many times have you create a loop, want to somehow assigned the value of I, for example: for an element, have found the last I it just returns the value?

Let's look at the error code, it creates five links text elements, each element of the value is I, and each element of the click event to eject the content for the I alert. To add the five elements to document body:

function addLinks() { for (var i = 0, link; i <5; i++) { link = document.createElement("a"); link.innerHTML = "Link " + i; link.onclick = function () { alert(i); }; document.body.appendChild(link); } } window.onload = addLinks;

Each element has the correct text, such as "Link 0", "Link 1" and so on, but you click each of the links, the value of alert is 5, which is obviously wrong, why? The reason is that, the variable I is increased by 1, but onclick event is not performed, is only applied to the I element, add 1.

Therefore, the cycle continues until it is equal to 5, this is the last value, I at this time, the function addLinks to exit. Later, when the onclick event is triggered only when the actual, the last value I.

All you need to do is create a closure, so, when you put the I value is applied to the elements of the onclick event, the exact value will be I in the trigger that moment. As shown below:

function addLinks() { for (var i = 0, link; i <5; i++) { link = document.createElement("a"); link.innerHTML = "Link " + i; link.onclick = function (num) { return function () { alert(num); }; } (i); document.body.appendChild(link); } } window.onload = addLinks;

The above code is not a problem. Click the first create a link element, 0 alter second to 1 and so on. The solution is applied to the inner function, the onclick event created a closure, a reference parameter num in there, that is the value of I.

Since the function call(Self-Invoking Functions)

Since the calling function is the automatic execution of the function (anonymous functions), and create the closure of their own, as shown in the following code:

(function () { var dog = "German Shepherd"; alert(dog); })(); alert(dog); // Returns undefined

The dog variable is only available in the scope. It can solve the circulation problem above us, and which is the basis of Yahoo JavaScript Module Pattern.

Yahoo JavaScript Module Pattern

The key points of Yahoo JavaScript module mode, it uses a self call a function to create a closed, therefore, with the private and public properties and methods become possible. A simple example, as shown below:

var person = function () { // Private var name = "Robert"; return { getName: function () { return name; }, setName: function (newName) { name = newName; } }; } (); alert(person.name); // Undefined alert(person.getName()); // "Robert" person.setName("Robert Nyman"); alert(person.getName()); // "Robert Nyman"

This code is very elegant. Now, you can decide what the public, what is hidden. The variable name is the outer hidden (external references in undefined), but through the getName and setName functions to access, because, they have created a closure, it references the name variables.

 

Other

 

Download Demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Webb at November 18, 2013 - 3:08 PM