In JavaScript, this behavior depends on how the function is called. ① In ordinary function calls, this points to a global object (window in the browser and global in Node.js), but undefined in strict mode; ② In object methods, this points to the object that calls the method, but if the method is called separately, this may lose the context; ③ The arrow function does not have its own this, which is inherited from the outer scope and is suitable for maintaining the consistency of this; ④ Use .bind(), .call(), and .apply() to explicitly bind this value, which is used to create binding functions, call immediately and pass parameters, call immediately and pass parameters in an array. The key to understanding this is how the function is called rather than how it is defined.
When you're working with JavaScript, the this
keyword can be one of the trickiest concepts to wrap your head around. It doesn't always refer to what you might expect, especially if you're coming from other programming languages. In short: this
refers to the context in which a function is called — not where it's defined.

Let's break this down into some common situations so you can better understand how this
behaves.
How this
works in regular function calls
In a normal function call (not inside an object method or class), this
usually points to the global object — which in browsers is window
, and in Node.js is global
. But if you're using strict mode ( "use strict"
), then this
will be undefined
.

For example:
function showThis() { console.log(this); } showThis(); // In browser: Window object (or undefined in strict mode)
So if you see this
pointing to something unexpected like the global object, check if the function is being called normally without any context.

A few things to note:
- This behavior changes when you're inside arrow functions (we'll get to that).
- If you're binding event handlers or callbacks, sometimes
this
loses its intended context unless explicitly bound.
this
inside object methods
When a function is part of an object (a method), this
refers to the object that owns the method. That makes sense because you're calling the function in the context of that object.
Example:
const user = { name: "Alice", greet() { console.log(`Hello, ${this.name}`); } }; user.greet(); // Hello, Alice
Here, this
refers to user
because the method is invoked on that object. But watch out for these gotchas:
If you extract the method and call it separately,
this
may becomeundefined
or point to the global object.const saysHi = user.greet; saysHi(); // Hello, undefined (in strict mode)
You can fix this by binding the method explicitly with
.bind(user)
or using an arrow function inside the method.
Arrow functions and this
Arrow functions do not have their own this
. Instead, they inherit this
from the surrounding lexical context — basically, the closest non-arrow function around them.
This is super useful when writing callbacks inside methods:
const user = { name: "Bob", greetLater() { setTimeout(() => { console.log(`Hi, ${this.name}`); }, 1000); } }; user.greetLater(); // Hi, Bob
If we had used a regular function instead of an arrow function inside setTimeout
, this
would point to the global object or undefined
, depending on strict mode.
So remember:
- Arrow functions are great for keeping
this
consistent - They're not suitable as object methods if you need to access the object via
this
Changing this
with bind, call, and apply
Sometimes you want to control exactly what this
refers to. For that, JavaScript gives us three tools: .call()
, .apply()
, and .bind()
.
-
.call(obj, arg1, arg2...)
runs the function immediately with a specificthis
-
.apply(obj, [args])
is similar but takes arguments as an array -
.bind(obj)
returns a new function withthis
permanently set
Use case example:
function introduction(lang) { console.log(`${this.name} knows ${lang}`); } const person = { name: "John" }; introduce.call(person, "JavaScript"); // John knows JavaScript introduce.apply(person, ["Python"]); // John knows Python const boundIntro = introduce.bind(person); boundIntro("Java"); // John knows Java
These methods are especially helpful when borrowing methods from other objects or setting up event handlers.
That's the general idea behind how this
works in JavaScript. It's all about where and how a function is called — not where it's written. Keep practicing and pay attention to how context changes in different scenarios. Once you get used to the rules, it becomes much more predictable.
Basically that's it.
The above is the detailed content of How the this Keyword Works in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

CommentsarecrucialinJavaScriptformaintainingclarityandfosteringcollaboration.1)Theyhelpindebugging,onboarding,andunderstandingcodeevolution.2)Usesingle-linecommentsforquickexplanationsandmulti-linecommentsfordetaileddescriptions.3)Bestpracticesinclud

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

JavaScripthasseveralprimitivedatatypes:Number,String,Boolean,Undefined,Null,Symbol,andBigInt,andnon-primitivetypeslikeObjectandArray.Understandingtheseiscrucialforwritingefficient,bug-freecode:1)Numberusesa64-bitformat,leadingtofloating-pointissuesli

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl
