JS in the This keyword

Source: Internet
Author: User

This is a keyword of JavaScript, and the value of this will change as the function is used in different situations. But there is always a principle that this refers to the object that invokes the function.


1. This in the global Code

alert (this);//window

This points to the global object.


2. As a simple function call

function Foocoder (x) {
this.x = x;
}
Foocoder (2);
alert (x);//global variable x value is 2

This points to the global object, which is window. In strict mode, it is undefined.


3. Method calls as objects

var name = "Clever coder";
var person = {
Name: "Foocoder",
Hello:function (STH) {
Console.log (this.name + "says" + sth);
}
}
Person.hello ("Hello World"),//foocoder says Hello World

This points to the person object, which is the current object.


4. As a constructor

New Foocoder ();

This points to the newly created object.


5. Intrinsic functions

var name = "Clever coder";
var person = {
Name: "Foocoder",
Hello:function (STH) {
var SayHello = function (sth) {
Console.log (this.name + "says" + sth);
};
SayHello (STH);
}
}
Person.hello ("Hello World"),//clever coder says Hello World

In an intrinsic function, this is not bound to the outer function object as expected, but is bound to the global object.


6. Use call and apply to set this

Person.hello.call (Person, "world");//apply and call are similar, except that the arguments are passed in an array, not separately.

Both are used to bind a function to a specific object, and this will naturally be set to the first parameter explicitly.

JS in the This keyword

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.