This keyword in Javascript and scope details

Source: Internet
Author: User

Javascript this keyword is generally not unfamiliar to everyone, but we need to think carefully about how to better use the Javascript this keyword. I hope this article will be helpful to the majority of programmers.

Summary

This series of blog posts focuses on some advanced applications that are often obfuscated in Javascript usage, including prototype, closure, scope, and this keywords. for a programmer who needs to improve their Javascript level, these must be mastered.

This section describes the this keyword and scope.

The Javascript source code in this article is downloaded from here.

Contents

Abstract introduction of this keyword about apply and callscope detailed descriptions of some conclusions. Postscript: References: source code of this Article

Introduction

As a programmer, you may have been used to the reference (or pointer) of the current object in object-oriented language, such as this in c ++ or self in python, of course, Javascript with OO attributes (Javascript is actually more of a so-called functional language) also has a pointer (or reference) to the object that references the current attribute ), that is, the this keyword.

To understand this keyword, if you only want to remember one sentence, it should be that this keyword always points to the owner object (Execution space) of the current function, for more information, see the following description.

So what is scope?

Wikipedia is interpreted as In computer programming, scope is an enclosing context where values and expressions are associated. chinese is the so-called scope, which specifies the context associated with a value or expression (the executable space that can be referenced ).

What is the relationship between scope and this? From the above definition, this always points to the object that currently references this function, and when you want to determine the currently referenced object, you have to figure out the scope of the current function. see the following analysis.

Javascript this keyword

See the following examples.

An example of python:

 
 
  1. ClassPerson (object ):
  2. """A personClass 
  3. """
  4. Def _ init _ (self, name ):
  5. Self. name = name # Here self points to the instantiated object, as shown in zhutao
  6. Def get_name (self ):
  7. ReturnSelf. name
  8. Zhutao = Person ("Zhutao")
  9. Print zhutao. name
  10. An example of Javascript:
  11.  
  12. Window. name ="Zhutao from window" 
  13. VarGet_name =Function(){
  14. Return This. Name;// The specific point of this can only be determined at runtime, that is, the object called during runtime. 
  15. };
  16. Alert (get_name ());// Output zhutao from window. The object called by get_name is window. 
  17. VarObj = {}
  18. Obj. name ="Zhutao from obj";
  19. Alert (get_name.apply (obj ));// Output zhutao from obj. We forcibly use apply to change the called object and direct it to obj. 
  20. VarInnerobj = {
  21. "Name":"Zhutao from innerobj" 
  22. };
  23. Innerobj. get_name = get_name;// Make the get_name method of innerobj point to the get_name function of global scope. 
  24. Alert (innerobj. get_name ());// Output zhutao from innerobj. At this time, this points to innerobj. 

From the simple example above, this is always the point of its call object at runtime, and it is also an important feature of Dynamic Language.

So how to determine the reference object to which this currently points? It is usually possible to judge as follows:

If you call the function in the global scope (see the following description to determine what global scope is), it points to the top-level Object window of boodle, for example, get_name ()

If there is a reference similar to this, innerobj. get_name () indicates that this points to innerobj.

If we use apply and call to forcibly point the referenced object, it will also clearly point to the forced object, such as get_name.apply (obj ).

Apply and call

The two keywords can be easily resolved to force conversion of this reference object (runtime space). the syntax of the two keywords is as follows:

 
 
  1. fun.call(object, arg1, arg2, ...)   
  2. fun.apply(object, [arg1, arg2, ...])  

The purpose of the two is the same (dynamically changing the runtime space of the function, or changing the object pointed to by this), but the call methods on the parameters provided to the function are different.

The sample code is as follows:

 
 
  1. var test_call_apply = function(name, gender, school){  
  2. alert(this.age + name + gender + school);  
  3. };  
  4. test_call_apply.call({age:24}, "zhutao", "male", "ISCAS");  
  5. test_call_apply.apply({age:24}, ["zhutao", "male", "ISCAS"]); 

Scope details

Let's take a look at the following examples:

 
 
  1. VarGlobal_scope ="I'm global";
  2. VarFun =Function(){
  3. VarFun_scope ="I'm in fun scope";
  4. ReturnInnerfun (){
  5. VarInner_func_scope ="I'm in the inner fun scope";
  6. ReturnGlobal_scope + fun_scope + inner_func_scope;// The reference here is important, please note 
  7. };
  8. };
  9. Alert (fun ()());

Pay attention to the above Code, where:

Global_scope: global scope

Fun_scope: It is located in the scope of a function.

Inner_func_scope is the scope of a function located in a function.

You can also embed functions to generate several scopes.

So there is a problem. Why can the innerfun method reference variables not in its own scope?

Before answering this question, we need to introduce a concept of scope chain. The so-called scope chain refers to a chain of priority and related scope formed in Javascript code.

The above code is used as an example,

For the global scope, it will create a global scope chain for itself (of course, this chain has only one scope ). for the scope of the fun function, it first establishes the same scope chain as global, and then adds its own scope (at this time, this chain has two scopes), similar to the following structure: global => fun for innerfun, in addition to the chain of the fun function, it will also add its own scope (of course, this chain has three scopes ), similar to this structure: global ==> fun ==> innerfunscope chain has the following features:

Every time a function is created in an ordered manner, a scope is automatically generated and added to its own scope chain. This chain is similar to a stack. When searching for variables, it always starts from the top. See:


The three parts correspond to the scope of the three variables in the above Code, and when you evaluate each variable, it is searched from top to bottom according to the scope chain in the figure, find the returned value or return undfined until the scope chain is lifted.

Now, answer the above question:

Actually, it is easy to understand. When calculating an expression, it will perform a search from top to bottom on its own scope chain. if it finds it, it will return this value immediately, if the entire chain is not found, undefined is returned.

This lookup mechanism determines that the scope at the front-end of the chain usually has a higher priority.

For example, when Javascript calculates global_scope + fun_scope + inner_func_scope; this expression, it searches for the scope chain shown in the preceding figure to determine the final result.

Notes

If you have figured out the above discussion, we should say that you already have a full knowledge base on the this keyword and scope, but we need to better use and understand these concepts in practice, in this way, the ability can be upgraded to another level, that is, the relationship between theory and practice.

See the following example:

 
 
  1. VarChange_color =Function(){
  2. This. Style. color ="Red";
  3. };
  4. Window. onload =Function(){
  5. VarText = document. getElementById ("Text");
  6. Text. onclick = change_color;// This points to the text object (dom object) 
  7. };
  8. // The following line of code is in the body 
  9. <Span id ="Another"Onclick ="Change_color ()"> My color will be changed2. </span>// Note that the inline script points to the window, which is not defined here. 

Note the following:

In inline event registration, this does not point to its own dom node, but to the window of global scope. this can be proved from the above example that this inline event registration is not desirable, the Unobtrusive Javascript (processing logic and page structure are separated) is recommended.
Javascript is a very powerful dynamic language. It is a functional language dressed in C language. If you just think of it as a C-like imperative language, your knowledge level is too low. If you can understand the essence of Javascript functional language, you are using Javascript to understand jQuery and other libraries, you can even write some Javascript on your own.

Postscript

The content of this series of plans has ended. In addition to this, I also want to write one or two additional advanced Javascript knowledge to end the series. The content may be written as follows:

Javascript functional language features explore the analysis of Javascript-related libraries some understanding and practices of Unobtrusive Javascript. In short, Javascript itself is a language worth exploring, and there are many points worth reading, I hope that this plan will be continuously completed in the future.

In fact, I have previously written about Django development and the Javascript of this series. I found that my related knowledge has been greatly improved while writing this content, at the same time, the website is not just as an independent scholar, but as a teacher. I hope readers who can see the content will also benefit. so I think I may write some other topics about computer science in the future, such:

Python must know that regular expressions must know that Web development is required. If this "Magnificent" plan is completed, I would like to achieve the knowledge base of a well-defined programmer.

This is a preliminary plan and I will expand it gradually. I hope you will continue to provide feedback.

Original article title: this keyword and scope, which must be known in javascript

Link: http://www.cnblogs.com/mindsbook/archive/2009/09/27/javascriptYouMustKnow-this-scope.html

  1. Analysis on using Javascript to obtain random colors
  2. What is JSON? Data format prepared for JavaScript
  3. 10 most commonly used JavaScript udfs
  4. Some extended thoughts on loading JavaScript events
  5. Summary of JavaScript usage: From BOM and DOM

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.