"Turn" 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.

1234 console.log(this.document === document); // true (document === window.document)console.log(this=== window); // true this.a = 37;  //相当于创建了一个全局变量aconsole.log(window.a); // 37
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.

1234 functionf1(){    returnthis} f1() === window; // true, global object

One more example, it's very thorough.

12345 functiontest(){ this.x = 1;  alert(this.x);}test(); // 1

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

12345 varx = 1;functiontest(){ alert(this.x);}test(); // 1

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

123456 varx = 1;functiontest(){ this.x = 0;}test();alert(x); //0

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

12345 functionf2(){    "use strict"; // see strict mode    returnthis; } f2() === undefined; // 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

12345678 var o = {      prop:37,      f: function () {           return this .prop;       } };   console.log (O.F ()); //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.

12345678 varo = {prop: 37};  function independent() {     return this.prop; } o.f = independent;  console.log(o.f()); // logs 37

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 points to O, and then uses P.A = 1; P.B = 4 Create the properties on the object p, then this.a,this.b can still fetch A and B on the object p when we invoke the method on the prototype. It should be noted here that the prototype of the P is O, we call P.F (), the invocation of the prototype chain O on the property F, the prototype chain of this can get the current object p.

12345 varo = {f:function(){ return this.a + this.b; }};varp = Object.create(o); p.a = 1; p.b = 4; console.log(p.f()); // 5 
Get/set method and this

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

1234567891011121314 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);      } }; Object.defineProperty(o, ‘modulus‘, {       //临时动态给o对象创建modules属性  get: modulus, 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 (which can be seen in this article's summary of the prototype chain), but when called 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

12345678910111213 function MyClass(){       this.a = 37; } var o = new MyClass();  console.log(o.a); // 37 function C2(){       this.a = 37;      return {a : 38};  } o = new C2();  console.log(o.a); // 38
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:

1234567891011 function add(c, d){     return this.a + this.b + c + d;  } var o = {a:1, b:3}; add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16     //第一个参数接收的是你想作为this的对象add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34 function bar() {     console.log(Object.prototype.toString.call(this)); } bar.call(7); // "[object Number]"
Bind method with this

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

123456789 function f(){     return this.a;  } var g = f.bind({a : "test"});   //想把某个对象作为this的时候,就把它传进去,得到一个新对象gconsole.log(g()); // test       //重复调用的时候,this已经指向bind参数。这对于我们绑定一次需要重复调用依然实现绑定的话,会比apply和call更加高效(看下面这个例子) var o = {a : 37, f : f, g : g};  console.log(o.f(), o.g()); // 37, test   //o.f()通过对象的属性调用,this指向对象o;比较特殊的是即使我们把新绑定的方法作为对象的属性调用,o.g()依然会按之前的绑定去走,所以答案是test不是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

"Turn" 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.