Home Web Front-end JS Tutorial What is the use of this in js? Usage of this keyword in js (with code)

What is the use of this in js? Usage of this keyword in js (with code)

Aug 17, 2018 pm 01:45 PM
javascript

The content of this article is about what is the use of this in js? The usage of this keyword in js (with code). The article introduces the understanding of this in js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

First of all, we must understand the several ways to call functions in JS:
1. Ordinary function call
2. Call as a method
3. Call as a constructor
4. Use the apply/call method to call
5.Function.prototype.bind method
6.es6 arrow function
Points: No matter how the function is called, who calls this function or method , this keyword points to whom, keep this in mind. !important

Below I will explain each method with examples!

1.Usage of this keyword: ordinary function call

(function fun(){
        this.name="segmentfault";
        console.log(this);  //window
        console.log(this.name);  //segmentfault        
})()
console.log(window.name);  //segmentfault  由此可见name属性属于window的属性。
Copy after login

In this code, the fun function is called as an ordinary function. In fact, fun is used as the global object window It is called by a method (everyone should know this), that is, window.fun(); so here the window object calls the fun method, then this in the fun function refers to the window, and the window also has another An attribute name, the value is segmentfault.

2.The usage of this keyword is as a method to call

var name="segmentfault";
var fun ={

name:"segmentfault-A",
showName:function(){
    console.log(this.name);  //输出  segmentfault-A
}
Copy after login

}
fun.showName();
//Here is the fun object calling the showName method. Obviously this keyword points to the fun object, so name

will be output.

var funA = fun.showName;
funA(); //Output segmentfault
//Here the fun.showName method is assigned to the funA variable. At this time, the funA variable is equivalent to an attribute of the window object, so When showNameA() is executed, it is equivalent to window.funA(), that is, the window object calls the funA method, so the this keyword points to window
Let’s look at it another way:

var funA={
    name:"segmentfault",
    showName:function(){
        console.log(this.name);
    }
}
var funB={
    name:"segmentfault-A",
    sayName:funA.showName
}

funB.sayName();  //输出 segmentfault-A
//虽然showName方法是在funA这个对象中定义,但是调用的时候却是在funB这个对象中调用,因此this对象指向funB
Copy after login

3.this The usage of the keyword is to call the constructor

function fun(name){
    this.name=name;
}
var funA = fun("segmentfault");   
console.log(funA.name); // 输出  undefined
console.log(window.name);//输出  segmentfault
//上面代码没有进行new操作,相当于window对象调用fun("segmentfault")方法,那么this指向window对象,并进行赋值操作window.name="segmentfault".

var funB=new fun("segmentfault");
console.log(funB.name);// 输出 segmentfault
Copy after login

4. The usage of this keyword is to call the call/apply method

Function in JS It is also an object, so functions also have methods. Inherited from Function.prototype to the Function.prototype.call/Function.prototype.apply method
The biggest function of the call/apply method is to change the pointing of this keyword.

Obj.method.apply( AnotherObj,arguments);

var name="segmentfault-A";
var fun={
    name:"segmentfault",
    showName:function(){
        console.log(this.name);
    }
}
fun.showName.call(); //输出 "segmentfault-A"
//这里call方法里面的第一个参数为空,默认指向window。
//虽然showName方法定义在fun对象里面,但是使用call方法后,将showName方法里面的this指向了window。因此最后会输出"segmentfault-A";
function FruitA(n1,n2){
    this.n1=n1;
    this.n2=n2;
    this.change=function(x,y){
        this.n1=x;
        this.n2=y;
    }
}

var fruitA = new FruitA("cheery","banana");
var FruitB={
    n1:"apple",
    n2:"orange"
};
fruitA.change.call(FruitB,"pear","peach");

console.log(FruitB.n1); //输出 pear
console.log(FruitB.n2);// 输出 peach
Copy after login

FruitB calls the change method of fruitA and binds this in fruitA to the object FruitB.

5. Function.prototype.bind() method for usage of this keyword

 var name="segmentfault-A";
function fun(name){
    this.name=name;
    this.sayName=function(){
        setTimeout(function(){
            console.log("my name is "+this.name);
        },50)
    }
}
var funA = new fun("segmentfault");
funA.sayName()  //输出  “my name is segmentfault-A”;
//这里的setTimeout()定时函数,相当于window.setTimeout(),由window这个全局对象对调用,因此this的指向为window, 则this.name则为segmentfault-A
Copy after login

Use bind() method below to output segmentfault

var name="segmentfault";
function fun(name){
    this.name=name;
    this.sayName=function(){
        setTimeout(function(){
            console.log("my name is "+this.name);
        }.bind(this),50)  //注意这个地方使用的bind()方法,绑定setTimeout里面的匿名函数的this一直指向fun对象
    }
}
var funA = new fun("segmentfault");
funA.sayName()  //输出  “my name is segmentfault”;
//这里的setTimeout()定时函数,相当于window.setTimeout(),由window这个全局对象对调用,因此this的指向为window, 则this.name则为segmentfault
Copy after login

Here setTimeout(function(){console.log(this.name)}.bind(this),50);, the anonymous function creates a new function after using the bind(this) method, no matter where this new function is Local execution, this points to fun, not window, so the final output is "my name is segmentfault" instead of "my name is segmentfault-A"

A few other things to note:
setTimeout/setInterval/When the anonymous function is executed, this points to the window object by default, unless the point of this is manually changed. In "JavaScript Advanced Programming", it is written: "The timeout call code (setTimeout) is executed in the global scope, so the value of this in the function points to the window object in non-strict mode, and in strict mode In mode, it points to undefined". This article is all in non-strict mode.

6. Eval function for usage of this keyword

When this function is executed, this is bound to the object in the current scope

var name="segmentfault-A";
var fun = {
    name:"segmentfault",
    showName:function(){
        eval("console.log(this.name)");
    }
}

fun.showName();  //输出  "segmentfault"

var a = fun.showName;
a();  //输出  "segmentfault-A"
Copy after login

7. Arrow function for usage of this keyword

The this point in es6 is fixed and always points to the external object, because the arrow function does not have this, so it cannot instantiate new by itself. At the same time, you cannot use call, apply, bind and other methods to change the pointer of this.

 function Timer() {
    this.seconds = 0;
    setInterval( () => this.seconds ++, 1000);
} 

var timer = new Timer();

setTimeout( () => console.log(timer.seconds), 3000);

// 3
   // 在构造函数内部的setInterval()内的回调函数,this始终指向实例化的对象,并获取实例化对象的seconds的属性,每1s这个属性的值都会增加1。否则最后在3s后执行setTimeOut()函数执行后输出的是0
Copy after login

Related recommendations:

Understanding of this keyword in js

About this keyword in js Understanding_javascript skills

A question about js this keyword_javascript skills

The above is the detailed content of What is the use of this in js? Usage of this keyword in js (with code). For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles