In layman's JavaScript

Source: Internet
Author: User

This is flexible in JavaScript, which may be different depending on the environment, or if the same function is called under different methods. But there is a general principle, that is, this refers to the object that called the function.

Here are my study notes, which are listed in 8 situations.

Global this (browser)

The This of the global scope refers to the global object, which is the window in the browser, and this object is global in node.

Console.log (this//  true (document = = = Window.document)console.log (This// this. A = PNs;     // Panax Notoginseng
This (browser) of the general function

General function declaration or function expression, directly call the function, this still points to the global object, in the browser This object is window, in node this object is global.

function F1 () {    returnthis;   // true, Global object

One more example, it's very thorough.

function  Test () {  this. x = 1; Alert (this//  1

To prove that this is a global object, make some changes to the code:

var x = 1; function Test () {alert (this//  1

The result of the operation is still 1. Change it a little bit again:

var x = 1; function Test () {  this. x = 0//0

But in strict mode, the general function calls this point to undefined, which is one reason why node should use strict mode.

function F2 () {    // See Strict mode    returnthis//  True
This of a function as an object method

This is more common as an object method to use.

In the following example, we create an object literal o,o has an attribute F, its value is a function object, and the function as the value of the object property is often called the method of the object. When a method call to an object is called, this time this point is directed to the object o

var o = {     PNs,     function() {         return this . Prop;      } };   // logs Notoginseng

We don't have to define the object as a function literal, like this, we only define an object o, if we call the Independent () function directly, this will point to the window, but we create a property f temporarily by assigning a value, and point to the function object, we still get 37.

var o = {prop:37function  Independent () {     return This = Independent;   // logs Notoginseng

So instead of looking at how a function is created, it will point to this object as long as the function is invoked as a method of the object.

This on the object prototype chain

In the following example: We first created an object o, which has an attribute F, the function as the value of the object property, we created an object through Object.create (o) p,p is an empty object, its prototype will point to O, and then use P.A = 1; P.B = 4 Creates a property on the object p, so when we call a method on the prototype, this.a,this.b still gets a and B on the object p. It is important to note that the prototype of P is O, we call P.F (), call the property F on the prototype chain O, the This on the prototype chain can get the current object p.

var o = {f:functionreturnThis this. B;}}; var p == 1= 4//  5
Get/set method and this

The This in the Get/set method typically points to the object where the Get/set method resides

functionmodulus () {returnMATH.SQRT ( This. Re * This. Re + This. im * This. im); } varo ={re:1, Im:-1, get phase () {returnMath.atan2 ( This. IM, This. Re); } }; Object.defineproperty (O,' Modulus ', {//temporarily dynamically create modules attribute Get:modulus for O object, enumerable:true, Configurable:true}); Console.log (O.phase, O.modulus); //logs-0.78 1.4142
This in the constructor

Using new to call MyClass as a constructor, this will point to an empty object, and the object's prototype will point to Myclass.prototype (the part of the prototype chain I'll summarize in the next blog post), but when called, the THIS.A = 37 is assigned. So the last this will be the return value (no return statement, or return is the basic type, this will be the return value), the second example return statement returns the object, then A = 38 as the return value

function MyClass () {       this. A = PNsvarnew  MyClass ();   //  function  C2 () {       this. A = PNs;        return {a:38};   New C2 ();   //
Call/apply method and this

In addition to different invocation methods, some methods of function objects can modify this, such as call/apply, that the function executes.

Call and apply are basically the same, except that the way that you send the arguments is flat, and apply is an array. As the following example

When do I use call and apply? For example, if we want to call Object.prototype.toString, but we want to specify a certain this, then we can use Object.prototype.toString.call (this) Such a way to invoke some methods that cannot be called directly. As the following example:

 function   add (c, D) { return  this . B + C + D;  var  o = {a:1, B:3 5, 7); //  1 + 3 + 5 + 7 = 16//The first parameter receives the object you want as this  add.apply (o, [10, 20]); //  1 + 3 + + =  
function bar () {Console.log ( Object.prototype.toString.call ( this ) ); } bar.call ( 7); //
Bind method with this

The Bind method is provided by ES5, so ie9+ supports

function f () {     returnthis. A;   var g = F.bind ({A: "Test"});    //        when test///Repeat is called, this already points to the bind parameter. This is more efficient than apply and call (see below)var o = {a:37, f:f,  g:g} for the binding that we need to be repeated at once. // The PNS, Test   //o.f () is called by the object's property, this points to the object o; The Special one is that even if we call the new bound method as the object's property, O.G () will still follow the previous binding, so the answer is test not G.
Summarize

When doing the project only to find out how important these basic concepts, if not put them one by one, it is really accidentally fell into the pit. Later I will also on the prototype chain, scope, inheritance, chain call, regular and other knowledge to summarize, welcome attention

In layman's 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.