I always think that I want to have a deep understanding of a language , It's not just about turning yourself into sir, It needs more time to temper . What can stand the test of time is worth having . Learn and use Javascript All in a flash 7 Years. , Recently, I felt that I had an epiphany about him , I don't know if it's a little late . This paper summarizes my opinions on JS Understanding of the role of , I hope my study will help .

In particular : This is from the other side ( The coverage of function fields ) To explain and explain the execution context .

One 、 Theoretical understanding of scope

From the beginning Javascript when , Whether it's school teachers , Or the old driver you work for , I will take you seriously ,Js There is a global scope in , And then it contains a lot of subdomains ( Such as : from function、object Create the scope of ), A child domain can easily access any object in the parent domain . Do you feel empty about this statement , Difficult to understand . Now I will use the vast territory to give an example :

Through the above Image, Let me show you the charm of scope step by step .

1. First , The earth : We are all familiar with , He contains you , I , And all the countries in the world ( It doesn't matter here , Otherwise Hold Unable to live ), This must be Js Global scope in . The earth contains the sky 、 air , just as Js In this paper, the global role includes Number、String、Function、Object、Boolean、Regex Objects such as .

2. also : China 、 The United States 、 North Korea is three equal sub domains , They all use the earth The rights of this global scope , Such as launching a satellite . But the United States no longer understands North Korea , It's impossible to do anything in North Korea . Such as Js Can be used in any child scope of Number、String Objects such as , But there is no way to directly call the method of a scope level object .

3. Again : As a Chinese citizen , China's internal resources can be used in accordance with the law ( It's just that you either pay for it , Or someone with a tax ), If you want to buy something American , It needs to new What a treasure 、 Or something from the east to make a reference between China and the United States , And then you know . Such as Js When you need to access the contents of a peer scope in , Then you need to get the references that were accessed .

4. Last :bind,apply,call, It can be understood in this way ,bind It's to buy things in regular shopping malls ( beforehand You can see physical objects ), and apply and call It's purchasing on behalf of others ( Only video ).bind Change an action, but this function does not execute immediately , and apply and call It will be executed immediately .

Two 、 The sample code illustrates the scope

function Card(){
this.name = 'name';
Card.prototype.getName =function(callback){
return this.name;
} function PostCard(card){
this.name = "postCard"
this.card =card;
PostCard.prototype.getName =function(){
var _name = this.card.getName(function(){
console.log("callback: " + this.name);
console.log(_name + " " + this.name);
} var card = new Card();
var postCard = new PostCard(card);

1. The above code Card and PostCard As mentioned in the first part, China 、 The United States , They all have a common parent scope , Namely window( The earth )

2. Card and PostCard Is a flat scope , Such as PostCard Of getName Methods want to visit Card Of getName Method , You need to get Card References to , Such as PostCard Constructors Incoming card Example is to accomplish this thing .

3. Card Of getName Accept one callback The higher-order function of ( This is another topic , Functional programming ), Here, just remember that the input is a type of function It's just a formal parameter of . And then in Card Of getName Method callback, But here you have to pay attention to , perform callback There is no way or means to specify its scope , therefore callback The execution scope is window( The earth ).

4. Output results :

name postname

3、 ... and 、 Example code description bind\apply\call

function Direction(){
this.direction = "mid";
Direction.prototype.set =function(val){
this.direction = val;
} var direction = new Direction();
var dir02 = new Direction();
direction.set.call(direction, "right");
direction.set.apply(dir02, ["bottom"]); console.log(direction.direction);
console.log(dir02.direction); //bind
var tmp = direction.set.bind(dir02);
tmp("bind after");

This example code provides a Direction function , Then on this( The current instance ) The binding direction attribute , And in Direction The prototype is bound with set Method ( For modification this Upper direction).

1. adopt new Created Direction Two examples of direction,dir02

2. adopt call and apply Change the direction of the scope , Conduct set Method execution ,call Yes direction example , and apply Yes dir02 Example . It also shows call And apply The difference between , It's a list for parameter transfer , One is an array .

3. Through the output, you will find that , Although it's all called direction Example of set Method , But what's changed is this.direction But the corresponding instance property .

4. adopt bind Method to direction Example of set Methods and dir02 Binding , Then execute the binding , You'll find that change is still dir02 Example of direction attribute .

5. Output results

bind after

Four 、 Summary of scope

1. There is only one global scope , But there are countless sub scopes .

2. Scope creation and execution :

2.1 Create a stage [ Function called , But the internal code hasn't started yet ]

2.2 establish Scope chain

2.3 Create variables   function And parameters

2.4 decision this Value ( That's the scope , Or execution context )

2.5 Code execution [ assignment 、 Look for function references and explanations / Execute code ]

On JavaScript More articles on the scope of

  1. Talking about JavaScript Scope of action

    I learned some time ago JavaScript Scope , This thing is JavaScript It's very important , It's also JavaScript Something very basic , Just like the basic martial arts in Shaolin , With the foundation , Only in this way can we learn peerless martial arts . What is the role of scope ? A set of well-designed ...

  2. JavaScript Variable scope

    All variables have global scope , Local variables have local scopes ( Note here that the parameters of the function are also local variables ) 1. In the body of the function , Local variables take precedence over global variables with the same name . My understanding is that when you define both local variables and global variables with the same name , The function body returns to ...

  3. On JavaScript( Four )—— Scope chain and declaration ahead of time

    Preface : It's graduation season , Tens of thousands of student party began to enter the society , Farewell to the ivory tower like school life . Often at every turning point of life , Emotional , deep feeling , All kinds of wonderful summaries of the past , Looking forward to the future . meanwhile , Also let many old “ garden ” After reading these ...

  4. JavaScript Scope and scope chain of

    Scope Scope is the accessible scope of variables and functions , That is, scope controls the visibility and life cycle of variables and functions . so to speak , When variables and functions can be used , When will it be destroyed , It's all about scope . JavaScript in , The scope of a variable has a global ...

  5. JavaScript The scope and promotion mechanism of

    JavaScript The scope and promotion mechanism of You know the following JavaScript What does the code output when it executes ? 1 2 3 4 5 6 7 8 var foo = 1; function bar() {     i ...

  6. Javascript Scope of action 、 Scope chains and closures

    One .javascript Scope in ① Global variables - Function body ② local variable - Declaration inside the function body 1) Function level scope javascript Local variables in a language are different from C#.Java Wait for advanced language , In these high-level languages ...

  7. In depth understanding of Javascript Variable scope

    I'm learning JavaScript Before variable scope of , We should make a few points clear : a.JavaScript The scope of a variable is based on its unique chain of scopes . b.JavaScript There is no block-level scope . c. The variables declared in the function are in the entire function ...

  8. 【 turn 】javascript Variable scope 、 Anonymous functions and closures

    The following passage is an excerpt , See that most people on the Internet use variables to be declared when they are used instead of at the top , It may also take into account js Look for variables that affect performance , Declare where you use it , Also very good. . stay Javascript in , When we write functions, we often need to ...

  9. NetEase JS Interview questions and Javascript Lexical scope description

    The calling object is at the front end of the scope chain , local variable ( Use... Inside a function var Declared variables ). Function parameters and Arguments Objects are all in scope within a function -- This means that they hide any properties of the same name higher up the scope chain . 2010 year 9 month 14 Japan , ...

  10. Verse 106 ,JavaScript Variable scope and memory

    JavaScript Variable scope and memory Learning points : 1. Variables and scopes 2. Memory problems JavaScript The variables of are very different from those of other languages .JavaScript Variables are loose ( Don't force type ) The essence , Decided that it only ...

Random recommendation

  1. equals

    package abstractClasses; import java.time.LocalDate; /** * Created by xkfx on 2016/12/20. */ public ...

  2. python How to achieve scoket signal communication

    To understand this network communication is really inseparable from the implementation of its implementation flow chart , I see. I know a lot about it , I think the blogger's painting is good , The address is http://www.cnblogs.com/wangcq/p/3520400.html 1. ...

  3. structure SEH To make a jump - Reprint

    The following code comes from CSDN Delphi One of the best people in the world (kiboisme Blue light ) procedure ExceptProc{ExceptionRecord,SEH,Context,DispatcherCo ...

  4. Shell Upload files to ftp

    Write a shell file , Upload the given file to the specified ftp. The code is as follows : #!/bin/bash # Used to upload files to ftp, Input parameters : file name ( Including paths ).ftp Of IP.ftp The port of . user name . password ip=$ ...

  5. HTML resources ( recommend )

    W3C Online verification tools :http://validator.w3.org/ (X)HTML nested rules :http://www.cnblogs.com/PeunZhang/archive/2012/03/11/2 ...

  6. WPF Next YUV Played D3D Solution


  7. ios Wechat payment v3

    V2 Version and V3 There's a big difference between versions . 1. Starting from the e-mail returned from the successful data audit of wechat payment merchants : You can get these parameters   appid,appSecret,partnerID,    partnerKey( From Ping ...

  8. C++ Find the smallest number in the rotation array

    Today I come across such a problem , It's interesting , Write it down. ! subject : Move the first elements of an array to the end of the array , We call it rotation of arrays . Enter a rotation of a non decrementing array , Output the smallest element of the rotation array . For example, an array of {3,4 ...

  9. c# linq The difference between the set , Combine , intersection , duplicate removal 【 turn 】

    using System.Linq;      List<string> ListA = new List<string>(); List<string> List ...

  10. &lt;input type=&quot;text&quot;&gt; and &lt;textarea&gt; The difference between

    In our development, we often need to use the input box , Usually the solution is <input type="text"> and <textarea>, So what's the difference between the two labels ?   One :<i ...