Using a piece of code to briefly describe how to use this in js

Source: Internet
Author: User

Today, a friend told me that he met the following code and asked me to explain the reason.
Copy codeThe Code is as follows:
Var name = "The Window ";
Var object = {
Name: "My Object ",
GetNameFunc: function (){
Return function (){
Return this. name;
};
}
};

Alert (object. getNameFunc (); the reason is that js's this is dynamically determined and has a direct relationship with your call method.

To put it simply, if you use the "object. function name" method when calling a function, this is the object before this. (vertex); otherwise, it is the window.
For example, when you call object. getNameFunc (), this in the getNameFunc function is the object you just declared. If you write
Copy codeThe Code is as follows:
Var func = object. getNameFunc;
Func ();

At this time, this in the getNameFunc function is window, although it is different from the call method of the same function, this is different.
In the same way, object. getNameFunc () returns a function reference. Adding a bracket is used to execute the function. Actually, it is equivalent to the following code:
Copy codeThe Code is as follows:
Var func = object. getNameFunc ();
Alert (func ());

There is no "object." form before the function, so when the function is executed, this is a window, and the result is very obvious.

I will write an article about js this in the future. You are welcome to pay attention to my CSDN blog tt361.

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.