Details of this usage examples in js and details of jsthis instances

Source: Internet
Author: User

Details of this usage examples in js and details of jsthis instances

This example describes how to use this in js. Share it with you for your reference. The details are as follows:

1. Point to window

Global Variables

Alert (this) // Returns [object Window]

Global Functions

function sayHello(){  alert(this);}sayHello();

2. Point to this object (in the global context, this points to window, this points to this object in an object, and this points to window in the closure)

Var user = "the Window"; var box = {user: 'The box', getThis: function () {return this. user;}, getThis2: function () {return this. user ;}}; alert (this. user); // the role walert (box. getThis (); // the boxalert (box. getThis2 (); // the Window (because the closure is used, this points to the window) alert (box. getThis2 (). call (box); // impersonate the box object (here this points to the box object)

3. Use apply and call to change this point of the function.

Function sum (num1, num2) {return num1 + num2;} function box (num1, num2) {return sum. apply (this, [num1, num2]); // this indicates that the window scope box impersonates sum for execution} console. log (box (10, 10); // 20

4. new Object

Function Person () {console. log (this) // point this to a new empty object} var p = new Person ();

I hope this article will help you design javascript programs.

Related Article

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.