The This in JavaScript

Source: Internet
Author: User

A function in JavaScript can be executed as a normal function or as a method of an object, which is the main reason for the richness of this meaning.

var name= "The window" var object={      Name: "My object",      getnamefunc:function ()      {              return function ()              {                        return this.name;}}      }

Why is this output the window and the following output is my Object?

var name= "The window" var object={      Name: "My object",      getnamefunc:function ()      {                 var = this;              return function ()              {                        return that.name;}}      }

Call Code alert (Object.getnamefunc () ());

JavaScript is a dynamic (or dynamic type) language, and the This keyword is executed to determine who it is. So this always points to the caller, that is, a reference to the ' Call object ' person.
The first part returns a function through the code: OBJECT.GETNAMEFUNC () call. This is a returned function, which is not a property or method of object, at which time the caller is window. So the output is the Window
The second part returns when the function Object.getnamefunc () is executed:
function ()
{
return that.name;
}
At this time the that=this. And this points to object, so that's point to object. No matter how many times you execute, he is a reference to object, so output my object

Because of the nature of its run-time bindings, this meaning in JavaScript is much richer, and it can be a global object, the current object, or any object, depending on how the function is called.

The invocation of a function in JavaScript has several ways: as an object method call, as a function call, as a constructor call, and with an apply or call invocation .

RELATED links:

this:http://www.ibm.com/developerworks/cn/web/1207_wangqf_jsthis/in layman's JavaScript

The This 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.