search
HomeWeb Front-endJS TutorialWhat is the use of this in js? Usage of this keyword in js (with code)

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的属性。

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
}

}
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

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

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

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

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

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"

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

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
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

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 Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor