This is an explanation: Who is this in JavaScript?

Source: Internet
Author: User
Tags modulus


Grammar
This

Global Objects

in the global execution context (outside the function), this refers to the global object.

Console.log (this.document = = = document); true//in Web browsers, the window object was also the global object:console.log (this = = = window); TRUETHIS.A = 37;console.log (WINDOW.A); 37

function

in the function, this value, depends on how to call this function

A simple call
Function F1 () {  return this;} F1 () = = = window; Global Object

In this example, this is not given any value. No declaration for strict mode, this must have a value to be given. By default, the global object is pointed to.
function F2 () {  "use strict";//See strict mode  return this;} F2 () = = = undefined;
In Strict mode, this is not declared, or undefined. He can also be any value, such as null or 42 or something else.As a method of an object

when a function is called as a method of an object, this points to the object itself.

in the following example, when O.F () is called, the this in the function points to the O object.

var o = {  prop:37,  f:function () {    return this.prop;  }}; Console.log (O.F ()); Logs 37

If the O object only declares a property, its F method is not defined at the beginning of the declaration, and then is directly assigned to other methods through O.F, the final effect is the same, just the pre-and post-definition problem, this still points to the O object:

var o = {prop:37};function Independent () {  return this.prop;} O.F = Independent;console.log (O.F ()); Logs 37

This example shows the invocation of the F function, which is performed as a member method of O.

We continue to see if we give O set another member attribute B to be an object, and look at this example, this time, who is this point? As we have already said, this is the object itself, so o.b as an object, and this object is also pointing to his own o.b.

O.B = {g:independent, Prop:42};console.log (O.B.G ()); Logs 42

This in the object prototype chain

The same concept is used in the object prototype chain

var o = {f:function () {return this.a + this.b;}}; var p = object.create (o);p. A = 1;P.B = 4;console.log (P.F ()); 5

In this example, the object P does not have its own property. It inherits the properties of O. So this time by P to call the F method, this point is P, which is the object prototype pattern. This is the prototype inheritance pattern in JavaScript.


This with getter and setter

Again, the same concept applies to getter and setter. A function uses a getter or setter to bind to an object's properties.

function modulus () {  return math.sqrt (this.re * this.re + this.im * this.im);} var o = {  re:1,  im:-1,  get phase () {    return math.atan2 (this.im, this.re);  }};o Bject.defineproperty (o, ' modulus ', {    get:modulus, enumerable:true, configurable:true}); Console.log (O.phase, O.modulus); logs-0.78 1.4142

as a constructor

. When a function is used as a constructor (isomorphic new constructs). This is the object that the function constructs.

> Tip: Although the default constructor returns an object reference, it can also return other objects.

/* * Constructors work like this: * * function Myconstructor () {*//Actual function   Body code goes here. *//Create properties on |this|  As *//desired by assigning to them. e.g., * this.fum = "nom";  *//et cetera ... * *//If The function has a return statement that *//returns an object, that object would be the *//result of the |new|  Expression. Otherwise, *//The result of the expression is the object *//currently bound to |this| *//(i.e., the common case is most usually seen). *} */function C () {this.a = 37;} var o = new C (); Console.log (O.A);  Logs 37function C2 () {this.a = 37; return {a:38};} o = new C2 (); Console.log (O.A); Logs 

In the last example (C2), because an object is returned during the constructor, the new object is discarded. ("this.a=37"; it's really useless code. But he wasn't exactly dead, because he was executed. But it didn't affect the execution of the code outside.)

call and the apply

A function internally uses this to bind its value to a special object by using the call or Apply method. All methods inherit Function.prototype.

function Add (c, D) {  return THIS.A + this.b + C + D;} var o = {a:1, b:3};//the first parameter is the object to use as//' this ', subsequent parameters is passed AS//argumen TS in the function Calladd.call (O, 5, 7); 1 + 3 + 5 + 7 = 16//The first parameter is the object to use as//' this ', the second is an array whose//members are U Sed as the arguments in the function calladd.apply (o, [10, 20]); 1 + 3 + 10 + 20 = 34

Let's take a look at the following. Bar.call (7) This line of code, the first parameter is a numeric value, then the bar method inside this is pointing to number. Here, you can try another line of code, new numbers. ToString ( ) to see the effect.

function Bar () {  Console.log (Object.prototype.toString.call (This));} Bar.call (7); [Object number]


Bind method

ECMAScript 5 was introduced Function.prototype.bind . bind is creating a new function instead of modifying a function. The behavior of the new function is the same as that of the original function, but his receiver is our given object, and the receiver of the original function remains unchanged.

function f () {  return THIS.A;} var g = F.bind ({A: "Azerty"}); Console.log (g ()); Azertyvar o = {a:37, f:f, G:g};console.log (O.F (), O.G ()); Panax Notoginseng, Azerty


as DOM event handling

When a function is used for event handling. His this will be the event that points to this element itself (using AddEventListener to add listener events, some browsers do not comply with the Convention and have their own set of practices.)

When called as a listener, turns the related element bluefunction Bluify (e) {  //Always True  console.log (this = = = E.currenttarget);   True when Currenttarget and target is the same object  console.log (this = = = E.target);  This.style.backgroundColor = ' #A5D9F3 ';} Get a list of every element in the documentvar elements = document.getelementsbytagname (' * ');//Add bluify as a click L Istener So when the//element was clicked on, it turns bluefor (var i=0; i<elements.length; i++) {  Elements[i].addev Entlistener (' Click ', Bluify, false);}


Inline Event handling

When code invokes processing on an element, this is the DOM element.

<button onclick= "alert (This.tagName.toLowerCase ()); >  Show this</button>

This is the button shown above. Remember that this is the only way to return this element.

<button onclick= "alert (function () {return This} ())); >  Show Inner this</button>

in this example, the intrinsic function this is not set, so it returns the Global Object window.


This article belongs to Wu Shi Wei's blog, the public number: Bianchengderen original article, reproduced when please indicate the source and the corresponding link: http://www.wutongwei.com/front/infor_showone.tweb?id =156, welcome everyone to spread and share.

This is an explanation: Who is this in JavaScript?

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.