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: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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.