this--in the diagram JS in-depth understanding of the this pointer in JavaScript

Source: Internet
Author: User
Tags script tag

You're not mistaken! JS wrote for so many years, this will still be mistaken! No mistake, JavaScript is the wrong answer!

............

Article comes from--Zhou Lujun's personal website: http://zhoulujun.cn/zhoulujun/html/webfront/ECMAScript/jsBase/2016_0329_7729.html

When writing Java, this is wrong, idea will directly error!

Like what......

But, Js,......idea, helpless ...

There are two important concepts in object-oriented programming: One is a class, the other is an instantiated object, a class is an abstract concept, a class is like a mold, and an instantiated object is a product that is made out of this mold, using an image metaphor. Instantiating an object is the real thing that we need, and the class and instantiation objects have a very close relationship, but in the use of the function of the class is absolutely no substitute for instantiating objects, like the mold and mold manufacturing products, the use of the same is not the same.

With the above code we can see that the this pointer in the Java language can only be used in the instantiation of the object, the this pointer is equal to the instantiated object, and this is followed by a dot operator, the point operator behind the things that this has, such as: name, work, hands, feet and so on.

In fact, the logical concept of this pointer in JavaScript is also an instantiation object , which is consistent with the this pointer in the Java language, but the this pointer in JavaScript is much more difficult to understand than this one in Java. The root cause I personally think there are three reasons:

Reason one:JavaScript is a functional programming language, it is strange that it also has this pointer, indicating that this function programming language is also an object-oriented language, said the specific point, JavaScript function is a high-order function, programming language, the higher-order function can be passed as an object , and the function in JavaScript can also be used as a constructor, this constructor can create an instantiated object, resulting in the execution of the method when the pointer to the this is constantly changing, difficult to control.

 Reason two: The global scope of JavaScript has a great effect on the this pointer, as shown in the Java example above, the this pointer will only take effect after using the new operator, but the this in JavaScript will take effect without a new operation. This will often point to the Global Object window.

  Reason three: The call and apply operators in JavaScript can change this point arbitrarily, which seems flexible, but this illogical approach destroys our understanding of the intent of this pointer and makes it difficult to understand the true point of this when writing code

The above three reasons violate the traditional method of this pointer, they have different from the traditional this principle of understanding, and in the actual development of three reasons are often intertwined, so,this, foggy ...

Introductory book: Professionnal Javascript for Web devolopers,--advanced saying this:

This always points to the object that called the Method!

var name= "Zhoulujun";
function say () {Console.log (this.name)} say (); Zhoulujun

In the script tag we can use the this pointer directly, the this pointer (pointing to the Window object, the result) is the Window object , even if you use the three equals sign they are equal. The global scope often interferes with our understanding of the characteristics of the JavaScript language, which is the essence of this interference:

In the JavaScript language, the global scope can be understood as a Window object , remembering that window is an object and not a class, that is, the window is an instantiated object . This instantiation process is done by the JavaScript engine when the page is loaded, and the entire page is condensed into the window object because the programmer cannot control and manipulate the instantiation process through the programming language, so we do not have the feeling of building the this pointer at development time, It's often overlooked, and that's what interferes with the way we understand this pointer pointing to the window in code.

Here this points to the Window object, so this.name->zhoulujun!


When the say function is executed, JavaScript creates an execute context (the execution contexts), and the execution context contains all the information needed to run the say function. The execute context also has its own scope chain, and when the function runs, the JavaScript engine starts by initializing the scope chain of the execution context from the scope chain of the say function.

This knowledge is recommended for reference:

http://blog.csdn.net/wangxiaohu__/article/details/7260668

Http://www.jb51.net/article/30706.htm

Here's a general note:

var myobj={name: "Zhoulujun", Fn:function () {Console.log (this.name)}}; Myobj.fn ();

The this here points to obj because FN () runs inside obj ...

And then we'll see ...

var name= "Zhoulujun"; function say () {Console.log (this.name) Console.log (This)}say (); function say2 () {var site= "zh    Oulujun.cn "; Console.log (this.site);} Say2 ();

myobj2={site: "zhoulujun.cn", Fn:function () {Console.log (This.site)}}

Here the this point is the object myObj2, because you call this FN is executed through MYOBJ2.FN (), that natural point is the object MyObj2, here again to emphasize that this point in the creation of the function is not the decision, when the call to decide, Whoever calls is pointing to who, be sure to figure this out.

Then, we go deeper (can't stand ...).

myobj3={site: "zhoulujun.cn", andy:{site: "www.zhoulujun.cn", Fn:function () {console.log (th Is.site)}}};myobj3.andy.fn ();

This is also the object point of objects, but the same this does not execute it, then you will certainly say that I said at the beginning of those are not all wrong? In fact, is not, just at the beginning of the inaccurate, I will add a word, I believe you can thoroughly understand this point of the problem.

If you can't understand it, just recite it like this!

Case 1: If there is this in a function, but it is not called by the object above, then this point is the window, it is necessary to explain that in the strict version of JS this point is not the window, but we do not discuss the strict version of the problem, You want to know that you can search the Internet yourself.

Scenario 2: If a function has this, the function is called by the object above, then this is the object at the top level.

Case 3: If there is this in a function, the function contains multiple objects, although the function is called by the outermost object, this point is only the object above it, and if you do not believe it, then we will continue to look at a few examples.

Is that the right thing to do? Go deep (can't stand it ...) Hate......

myobj3={site: "zhoulujun.cn", andy:{site: "www.zhoulujun.cn", Fn:function () {    Console.log (This) Console.log (This.site)}}};//MyObj3.andy.fn ();    var Fn=myobj3.andy.fn; FN ();

In fact, the FN here is equivalent to

Fn:function (age) {

Console.log (This.name+age);

}

Let's talk about how functions are defined: declaring functions and function expressions

Our first case defines the way the function is defined in the JavaScript language, which is called the declarative function, the second way to define the function is called the function expression, which we usually think is equivalent, but they are actually different, and this difference often makes us confuse the use of this pointer, Let's look at the following code:

Why say can be executed, say3 can not? That's because:

Why SAY3 Print the result is undefined, I mentioned in the previous article undefined is in the memory of the stack has the name of the variable, but there is no stack of variable values, while the heap area is no specific object , This is the result of the JavaScript engine pre-loading the scan variable definition, but Ftn01 's printing results are surprisingly, since the finished function definition is printed, and the code is not executed sequentially, this can only indicate one problem:

In JavaScript, where functions are defined by declaring functions, the JavaScript engine completes the function definition and assignment operations in the preprocessing process, where I add the preprocessing features in JavaScript, in fact, preprocessing is related to the execution environment, In the previous article, I mentioned that there are two main types of execution environment: the global execution environment and the local execution environment, the execution environment is embodied by the context variables, in fact, this process is done before the function execution, preprocessing is another way to construct the execution environment, in summary, the main purpose of preprocessing and constructing the execution environment is to define the variable definition , the boundary of the variable is distinguished, but when the global scope constructs or the global variable preprocessing is somewhat different for the declaring function, the declaring function completes both the variable definition and the assignment operation, so we see the result of the above code. Because declaring a function is done at the time of global scope construction, declaring a function is a property of the Window object, which explains why we declare a function to be a window object regardless of where it is declared.

It is recommended to take a look at the execution order of a--java class:

Http://www.zhoulujun.cn/zhoulujun/html/java/javaBase/7704.html

In fact, any anonymous function in the JavaScript language is a Window object , and they are all defined and assigned at the time of global scope construction , but the anonymous function is a function variable with no name. But when the anonymous function is defined, it returns its own memory address, and if a variable receives the memory address, then the anonymous function can be used in the program, because the anonymous function is also defined and assigned at the time of the global execution environment, so the anonymous function's this point is also the Window object , so the above code executes when FN's this is pointing to window, because the JavaScript variable name is valid in that scope, the stored function of the heap is fixed in the global execution environment, the name of the variable is just a reference.

A similar situation (face test like this test!) )...... Like what:

This is all pointing to the instantiated object , so much so that this is all pointing to the window because only one instantiation is done at a time, and this instantiation is instantiating the Window object, so this is pointing to window. We have to change this from window to another object, so we have to instantiate the function, so how do we instantiate the function of JavaScript? The answer is to use the new operator.

Look again at the constructor:

function User () {this.name= "Zhoulujun"; Console.log (this);} var andy=new User (); Console.log (Andy.name)

Why Andy's name is Zhoulujun, that is: because:

The New keyword can change the point of this, which points to the object Andy,

When did Andy become a smecta, Oh,no,is Object?

Because the new keyword is used to create an object instance (important thing to read silently three times)

Here we use the variable Andy to create a user instance (equivalent to copying a copy of the user into the object Andy), at this time just create, and do not execute, and call this function user is the object Andy, then this point is the object of the Nature Andy, So why is there a name in the object user, because you have copied a copy of the user function to the object Andy, using the new keyword as the copy.

Java Program Ape: Class user=new User (); The familiar wood has ...

function a function that can also represent an object is a function that can also be used as a constructor, JavaScript constructors I often think of as combining classes and constructors, of course in JavaScript There is no class concept in the language specification, but this understanding can be a difference between a constructor and a normal function, which makes it easier to understand .

Here I post an explanation of the new operator in JavaScript advanced programming:

The new operator causes the constructor to change as follows:

1. Create a new object;

2. Assign the scope of the constructor to the new object (so this one points to the new object);

3. Execute the code in the constructor (add attributes for this new object);

4. Returning new objects



......

Mother: Read so awkward, unknown to feel Li ...... Look at the picture ... Not yet

Don't understand......

var myobj5={name: "Andy"};var myobj6=new Object (); myobj6.name= "Andy"; function Say5 (name) {Console.log (name)} var say6=new Function ("name", "Console.log (name)"); Console.log (MYOBJ5) Consol E.log (MYOBJ6) say5 ("Andy"); Say6 ("Andy");

Still do not understand, please grandma buy a piece of tofu, hit dead forget ...

The 4th is also to focus on, remember that the constructor is new operation, to let new normal function is best not to write the return in the constructor, no return of the constructor is executed according to the above four points , with the return situation is complex

Return this king eight eggs ...

So I do ...

Does it has a to is like this? Tell me why are there something I have missed?

Tell me why, cos I don ' t understand .......

That's because ... because of u? No return ...

So: If the basic type is returned, it will be discarded ... Can only return object type ... typeof xx = = = "Object"

Did you see called? What the heck!!

In fact, the new keyword creates an empty object, and then automatically calls a function apply method, which points to this empty object, so that the inside of the function will be replaced by this empty object.

var a={name: "Andy", Site: "zhoulujun.cn", fn:function (age) {Console.log (this.name+age);    }};var b={Name: "Zhoulujun", Site: "www.zhoulujun.cn", fn:function (age) {Console.log (this.name+age); }};a.fn (2); Andy2a.fn.call (b,2)//zhoulujun2a.fn.apply (b,[2])//zhoulujun2

Of course, there's bind ...

............

Written here, can not see, logic is a bit confusing, some from the predecessor where the reference.

There's time to sort it out, then, to talk about closures (... closer

Reference article:

http://blog.jobbole.com/81018/

http://blog.jobbole.com/74110/

Http://www.cnblogs.com/aaronjs/archive/2011/09/02/2164009.html#commentform

Http://www.codeceo.com/article/javascript-this-pointer.html

Article comes from--Zhou Lujun's personal website: http://zhoulujun.cn/zhoulujun/html/webfront/ECMAScript/jsBase/2016_0329_7729.html

this--in the diagram JS in-depth understanding of the this pointer in JavaScript

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.