A deep understanding of the scope of this in Javascript and a deep understanding of javascript

Source: Internet
Author: User

A deep understanding of the scope of this in Javascript and a deep understanding of javascript

This guy often gets dizzy when using Javascript. For most developers with OOP development experience, this is the identifier that references common elements in the current scope, but in Javascript it looks strange, because it is not fixed, it changes with the change of its execution environment. In Javascript, this always points to the object that calls its method.

Here is a simple example:
Copy codeThe Code is as follows:
Function test (){
Alert (this );
}
Var obj = function (){
Var name = 'testobj ';
}
Obj. objTest = test;
Test ();
Obj. objTest ();

Put this code in HTML to run this page. You will see a warning [object window] First, and a second warning.

Copy codeThe Code is as follows:
Var obj = function (){
Var name = 'testobj ';
}

We first define a test () method, and call the alert () method inside the method to display this, and then define an obj function object, add a private field name to it, and add a static method objTest () to it. This function directly points to the test () function.

Call the test () and obj. objTest () methods respectively. The first warning box prompts the Window object, and the second prompt shows the code of the obj function we have defined. This indicates that the value of this is different when the test function is executed twice!

This indicates that when the objects that call a function are different, the internal this keyword indicates different objects. It is worth noting that Javascript is an object-based language, when our variables or functions are defined under the root of the <script> </script> label, they are equivalent to adding corresponding properties or methods to the window object, so when we use the function test () {} Code to define a function, it is equivalent to adding a new function to the window object, that is, window. test () function.

We can do an experiment:

Copy codeThe Code is as follows:
Function test (){
Alert (this );
}
Alert (test = window. test );

The warning box prompts true, which means that when we call the test () function, it is equivalent to calling window. test (). Therefore, when we call the test () function, the object that calls this function is actually a window object, and this refers to a window object, so we use alert (this) the pop-up warning Window content is [object Window]. We set obj. objTest = test is equivalent to obj. objTest () points to test (), so when we call obj. the objTest () Function calls the test () Function in obj, so now this refers to the obj object, prompting that the obj Function is the code we see.

This should be explained almost as well. The above example may be too abstract and cannot be imagined when it can be used. Now let's assume a requirement, let's look at a practical example.

Assume that the color of all hyperlinks on the current page should be changed to red after clicking, and implemented in Javascript. The general idea is to obtain all the <a> labels on the page, traverse all the <a> labels, and register a click event for each of them, after an event is triggered, we set its color value to red.

The sample code is as follows:
Copy codeThe Code is as follows:
// Change the color
Function changeColor (){
This. style. color = '# f00 ';
}
// Initialize and register events for all a tags
Function init (){
Var customLinks = document. getElementsByTagName ('A ');
For (I in customLinks ){
// You can also use the event listener to register events
// To be compatible with IE, FF, and other browsers, you may need more code.
CustomLinks [I]. onclick = changeColor;
}
}
Window. onload = init;

Add this code to the HTML document and add some hyperlinks to the document. When the hyperlink is clicked, the color turns red. Here we define changeColor () when you click a hyperlink in a function to trigger a function, this keyword indicates the current hyperlink. If you directly call the changeColor () function browser, an Error is reported, indicating that 'this. style' is null or not an object or undefined.

I don't know if I can help you understand the this keyword in Javascript when reading the article? Or are you impatient? (: P)

In fact, to have a deeper understanding of this issue, we must have a deeper understanding of the Javascript scope and scope chain.

Scope, as its name implies, refers to the code space where an attribute or method has access permissions. Simply put, this variable or method applies to the code. In most OOP projects, there are three scopes: public, private, and protect, which are not explained in detail here. If you have OOP experience, you should have an in-depth understanding. Here I want to talk about the three scope types, which are almost meaningless to Javascript, because Javascript only has one public scope and the scope in Javascript is maintained in the function. For example:

Copy codeThe Code is as follows:
Var test1 = 'globle variable ';
Function example (){
Var test2 = 'example variable ';
Alert (test1 );
Alert (test2 );
}
Example ();
Alert (test1 );
Alert (test2 );

According to our previous explanation, the test1 variable here is equivalent to an attribute of window, so it will take effect in the entire window scope, while test2 is declared in the example () function, therefore, its scope is maintained inside the example () method. If test2 is called outside the function, an error is prompted. Test1 is called in example.

Here is another example:
Copy codeThe Code is as follows:
Var test = 'globle variable ';
Function example (){
Var test = 'example variable ';
}
Example ();
Alert (test );

What is the result of this example? Yes, the warning box will prompt "globle variable", because the test variable in the example () function is only in the internal scope and does not affect the external test variable. What if we remove the var keyword of the test variable in example? You can try it on your own.

This involves another concept, namely the scope chain. The scope chain is the path where variable values can be determined. The preceding example shows that the var keyword is used to maintain the scope chain. If the variable uses the var keyword declaration, it can be viewed as the end point of the scope chain. The definitions of the same function parameters also play a similar role.

Speaking of this, do you have a clear understanding of this weird genie? According to its simple interpretation, this always points to the object that calls the function where it is located. Based on the scope and scope chain, we will clearly determine the true face of this. Next, let's start with a simple change in that example:

Copy codeThe Code is as follows:
Function test (){
Alert (this );
}
Var obj = function (){
Var name = 'testobj ';
}
Obj. objTest = test;
Obj. objTest2 = function (){
Test ();
}
Test ();
Obj. objTest ();
Obj. objTest2 ();

What do you expect to prompt? You can run it for a moment (: P );

Since this is changed based on the change of the object in which the function is called, can we force change the object to be called? The answer is yes. later articles will introduce this part, as well as the implementation methods and closures of different types of data members in Javascript.

I have some experience and experience in the course of learning. I wrote it to share it with you and check my own shortcomings. If you have any questions, please criticize and advise me. Thank you very much!


Javascript this scope details

From the underlying js syntax, this indicates the prototype of the current object.
That is, if you call a method:
Function fun (){
This. val = "";
}
Fun ();
So here this refers to the prototype of the fun method object, which is generally a method object.
If it is to give you an Html Button registration time method, then you only want this button.

Therefore, the objects pointed to by this can be dynamically changed, not static. The answer on the first floor is only the browser's default Prototype.

What is the scope of this in javascript?

See how to call, if
Ge. StringBuilder () // then Ge
Ge. StringBuilder. call (some) // some
New Ge. StringBuilder () // this
Var fn = Ge. StringBuilder; fn () // The window

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.