Home > Web Front-end > JS Tutorial > A detailed explanation of this in JavaScript

A detailed explanation of this in JavaScript

黄舟
Release: 2017-03-03 15:34:51
Original
947 people have browsed it

This in JavaScript is relatively flexible. This may be different depending on different environments or when the same function is called in different ways. But there is a general principle, That is, this refers to the object that calls the function.

Series Catalog

  • Introduction to JavaScript’s Closure (Closure)

  • Introduction to JavaScript’s this

  • In-depth introduction to the prototype chain and inheritance of JavaScript

The following are my study notes, which are listed into 8 situations.

Global this (browser)

This in the global scope generally points to the global object. In the browser, this object is window. In node, this object is global.

console.log(this.document === document); // true (document === window.document)
console.log(this === window); // true 
this.a = 37;  //相当于创建了一个全局变量a
console.log(window.a); // 37
Copy after login

This of general functions (browser)

For general function declarations or function expressions, if the function is called directly, this still points to the global object. In the browser, this object is window. In node, this object is global.

function f1(){  
  return this;  
} 
f1() === window; // true, global object
Copy after login

Give another example, it will be very clear after reading it

function test(){
 this.x = 1;
  alert(this.x);
}
test(); // 1
Copy after login

In order to prove that this is the global object, make some changes to the code:

var x = 1;
function test(){
 alert(this.x);
}
test(); // 1
Copy after login

The running result is still 1. Change it again:

var x = 1;
function test(){
 this.x = 0;
}
test();
alert(x); //0
Copy after login

But in strict mode, when a function is called, this points to undefined. This is one reason why node uses strict mode.

function f2(){  
  "use strict"; // see strict mode  
  return this; 
} 
f2() === undefined; // true
Copy after login

This as a function of an object method

It is more common to use this as an object method.

In the following example, we create an object literal o. There is an attribute f in o, and its value is a function object. We often call the function as the value of the object attribute. method. When called as a method of an object, this points to the object o

var o = {  
   prop: 37,  
   f: function() {    
     return this.prop;    
  } 
};  

console.log(o.f()); // logs 37
Copy after login

We do not necessarily have to define an object like a function literal. In the following case, we only define an object o. If If the independent() function is called directly, this will point to window, but when we temporarily create a property f through assignment and point it to the function object, we still get 37.

var o = {prop: 37}; 

function independent() {  
   return this.prop; 
} 

o.f = independent;  
console.log(o.f()); // logs 37
Copy after login

So it doesn’t depend on how the function is created, but as long as the function is called as a method of the object, this will point to the object.

This on the object prototype chain

In the following example: we first create an object o, which has an attribute f and a function As the value of the object attribute, we create an object p through Object.create(o), p is an empty object, and its prototype will point to o, and then use p.a = 1; p.b = 4 to create the attributes on the object p, then When we call the method on the prototype, this.a, this.b can still get a and b on the object p. What needs to be noted here is that the prototype of p is o. When we call p.f(), we call the attribute f on the prototype chain o. This on the prototype chain can get the current object p.

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
Copy after login

get/set method and this

This in the get/set method will generally point to the object in the get/set method

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
Copy after login

In the constructor this

If you use new to call MyClass as a constructor, this will point to an empty object, and the prototype of this object will point to MyClass.prototype (see this article for a summary of the prototype chain), but the call At that time, the assignment of this.a = 37 was made, so in the end this will be used as the return value (if no return statement is written, or if the return is a basic type, this will be used as the return value). In the second example, the return statement returns the object, Then a = 38 will be used as the return value

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
Copy after login

The call/apply method and this

In addition to different calling methods, some methods of the function object can modify the this of the function execution, such as call/ apply.

There is basically no difference between call and apply, except that call passes parameters in a flat way, while apply passes an array in. As in the following example

When should we 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) to call some methods that cannot be called directly. Take the following example:

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]"
Copy after login

bind method and this

bind method is provided starting from es5, so ie9+ only supports

function f(){  
   return this.a;  
} 

var g = f.bind({a : "test"});   //想把某个对象作为this的时候,就把它传进去,得到一个新对象g
console.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
Copy after login

Summary

Doing projects Only then did I realize how important these basic concepts are. If you don’t implement them one by one, you will really fall into a pit accidentally. In the future, I will also summarize the prototype chain, scope, inheritance, chain call, regularity and other knowledge. Welcome to pay attention to

. The above is the detailed explanation of this in JavaScript. For more related content, please pay attention to PHP Chinese Net (www.php.cn)!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template