Home > Web Front-end > JS Tutorial > In-depth understanding of the scope of this in Javascript_javascript skills

In-depth understanding of the scope of this in Javascript_javascript skills

WBOY
Release: 2016-05-16 16:39:48
Original
1055 people have browsed it

Everyone is often confused by this guy when using Javascript. For most developers with OOP development experience, this is an identifier that refers to ordinary elements in the current scope, but in Javascript it seems weird because it is not fixed, but changes with it. changes due to changes in the execution environment. In Javascript this always points to the object on which the method is called.

Give a simple example:

Copy code The code is as follows:

function test(){
alert(this);
}
var obj=function(){
var name='testObj';
}
obj.objTest=test;
test();
obj.objTest();

Put this code into HTML and run this page. You will see a warning [object window] first, and then a second warning.

Copy code The code is as follows:

var obj=function(){
var name='testObj';
}

We first defined a test() method, and called the alert() method inside the method to display this. Then we defined an obj function object, added a private field name to it, and added A static method objTest() is created, and this function points directly to the test() function.

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

This shows that when the object calling the function is different, the object referred to by the internal this keyword is different. It should be noted here that Javascript is an object-based language. When our variables or functions are defined under the root of the <script></script> tag, it is actually equivalent to adding corresponding attributes or methods to the window object. So when we use the function test(){} code to define a function, it is actually equivalent to adding a new function to the window object, namely the window.test() function.

We can do an experiment:

Copy code The code is as follows:

function test(){
alert(this);
}
alert(test===window.test);

The warning box prompt will be true, which means that when we call the test() function, we are equivalent to calling window.test(). So when we call the test() function, the object that calls this function is actually the window object, and this refers to the window object, so the content of the warning window that pops up when we alert(this) is [object Window]. We set obj.objTest=test which is equivalent to pointing obj.objTest() to test(), so when we call the obj.objTest() function, it is equivalent to calling the test() function in obj, so now this refers to obj object, what is prompted is the function of obj, which is the code we see.

This should be explained almost enough. Maybe the above example is too abstract and I can’t imagine the circumstances in which it can be used. So let’s assume a requirement now and make a more practical example.

Suppose that the color of all hyperlinks in our current page should be changed to red after being clicked, and this is implemented using Javascript. The general idea should be to get all the tags in the page, then traverse all the tags, and register a click event for each one. After the event is triggered, we set its color value to red.

The sample code is as follows:

Copy code The code is as follows:

//Change color
function changeColor(){
this.style.color='#f00';
}
//Initialize, register events for all a tags
function init(){
var customLinks=document.getElementsByTagName('a');
for(i in customLinks){
//You can also use event listeners to register events
//Due to compatibility with IE, FF and other browsers, more code may be required, you can write it yourself
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 will turn red. The this keyword in the changeColor() function we defined here is triggered when the hyperlink is clicked. function, it refers to the current hyperlink. And if you call the changeColor() function directly, the browser will report an error, prompting an error such as Error: ‘this.style’ is null or not an object or undefined.

I wonder if this can give you who are reading the article some understanding of the this keyword in Javascript? Or are you impatient? (:P)

In fact, if you want to truly have a deeper understanding of this issue, you must have a deep understanding of the scope and scope chain of Javascript.

Scope, as the name suggests, refers to the code space that a certain attribute or method has access permissions. Simply put, it is the scope of application of this variable or method in the code. In most OOP, there are three main scopes: public, private, and protect. I will not explain the three scopes in detail here. If you have OOP experience, you should have an in-depth understanding of them. What I want to say here is that these three scope types are almost meaningless to Javascript, because there is only one public scope in Javascript, and scopes in Javascript are maintained within functions. For example:

Copy code The 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 what we explained earlier, the test1 variable here is equivalent to an attribute of window, so it will work within the entire window scope, while test2 is declared inside the example() function, so its scope is Maintained inside the example() method, if the test2 browser is called outside the function, an error will be prompted. There is no problem calling test1 inside example().

Based on this, let’s give another example:

Copy code The code is as follows:

var test='globle variable';
function example(){
var test='example variable';
}
example();
alert(test);

What will be the result of running this example? Yes, the warning box will prompt "globle variable" because the scope of the test variable inside the example() function only remains internal and will not affect the external test variable. What if we remove the var keyword from the test variable inside example()? You can try it yourself.

Speaking of this, another concept is involved, that is, the concept of scope chain. A scope chain is a path through which the value of a variable can be determined. As can be seen from the above example, the var keyword is used to maintain the scope chain. If a variable is declared using the var keyword, it can be regarded as the end point of the scope chain. The definition of the formal parameters of the same function will also play a similar role.

Speaking of which, do you have a clearer understanding of this weird guy? According to its simple interpretation, this always points to the object that calls the function in which it is located. According to the scope and scope chain, we will clearly determine the true face of this. At the end, here is a simple variation of the example at the beginning:

Copy code The 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 think it will prompt? You can try running it (:P);

Since this changes based on the change of the object that calls its function, can we forcefully change its calling object? The answer is yes. Future articles will introduce this part, as well as the implementation of different types of data members in Javascript, closures and other concepts.

Writing down some of my experiences and insights in the learning process is to share with everyone and also to examine my own shortcomings. If there are any problems with what I wrote, please criticize and give me advice. Thank you very much!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template