Through a piece of code to simply say the use of this in JS _ basic knowledge

Source: Internet
Author: User
Today, a friend said that the following code, let me help explain why
Copy Code code 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 this is dynamically determined by JS, which is directly related to the way you call it.

Simply put, if you call a function by using the "object. Function Name" method, then this is this. (dot) before the object, otherwise it is window.
For example, when you call Object.getnamefunc () the This in the body of the Getnamefunc function is the object just declared. If you write
Copy Code code as follows:

var func = Object.getnamefunc;
Func ();

This is the window in the body of the Getnamefunc function, although the difference of this is determined by the way that the same function is invoked.
In the same way, Object.getnamefunc () returns a function reference, with a bracket that lets the function execute. Actually corresponds to the following code
Copy Code code as follows:

var func = Object.getnamefunc ();
Alert (func ());

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

Later I will write an article about JS this, welcome everyone 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.