This pointing in JavaScript depends on the way the function is called, not the location of the definition. 1. In the global context, this points to the global object (window in the browser, undefined in strict mode); 2. When called as an object method, this points to the object, but calling it alone will lose the context, which can be solved by bind or arrow functions; 3. In the constructor this point to the newly created instance; 4. The arrow function has no this itself, and it inherits the outer context and is not suitable for methods that need to bind the object; 5. In event processing, this usually points to the DOM element that triggers the event, but using arrow functions inherits the outer context. Mastering these rules can help avoid common mistakes.
In JavaScript, the this
keyword can be a bit confusing because its value depends on how a function is called. It doesn't refer to the function itself or its scope, but rather to the object that "owns" the method at runtime.

Let's break it down with some common scenarios and practical advice.
Global Context: this
Points to the Global Object
When you're in the global execution context (outside of any function), this
refers to the global object. In a browser environment, that's the window
object. In Node.js, it's the global
object.

console.log(this); // In a browser, logs the window object
This behavior changes in strict mode:
"use strict"; console.log(this); // Logs undefined in a function, or the global object outside
Tip: Don't rely on this
in the global scope — it can behave differently across environments, especially when modules or bundlers are involved.

Method Invocation: this
Refers to the Owner Object
When a function is called as a method of an object, this
inside that function refers to the object the method belongs to.
const person = { name: "Alice", greet: function() { console.log("Hello, " this.name); } }; person.greet(); // Logs "Hello, Alice"
Common mistake: If you assign the method to a variable and call it separately, this
loses context:
const greetFunc = person.greet; greetFunc(); // Logs "Hello, undefined" in non-strict mode
To fix this, bind the context explicitly:
- Use
.bind(person)
when assigning the function - Or use arrow functions if you don't want to bind manually
Constructor Functions: this
Refers to the New Instance
When a function is used as a constructor with the new
keyword, this
refers to the newly created object.
function Person(name) { this.name = name; } const alice = new Person("Alice"); console.log(alice.name); // "Alice"
Here's what happens under the hood:
- A new empty object is created
-
this
inside the constructor points to that new object - The object is linked to the constructor's prototype
- The new object is returned automatically unless you return a different object
Note: If you forget new
, this
will point to the global object (or undefined
in strict mode), which can lead to bugs.
Arrow Functions: this
Is Lexically Scoped
Arrow functions do not have their own this
. Instead, they inherit this
from the surrounding lexical context.
const person = { name: "Bob", greet: () => { console.log("Hi, " this.name); } }; person.greet(); // Logs "Hi, " (name is undefined)
Because the arrow function uses the outer this
, which in most cases is the global object or undefined
, it's not suitable for object methods where you need access to the object itself.
Best practice: Use regular functions for object methods and arrow functions when you want to preserve the outer this
— like inside callbacks.
Event Handlers: this
Often Points to the DOM Element
When using this
inside an event handler attached via traditional DOM properties ( onclick
, etc.), this
typically refers to the element that triggered the event.
<button onclick="console.log(this)">Click me</button>
That logs the <button>
element itself.
But if you attach the handler via addEventListener
, the same rule applies unless you bind another context:
document.querySelector("button").addEventListener("click", function() { console.log(this); // Logs the button element });
With arrow functions again, this
is inherited:
document.querySelector("button").addEventListener("click", () => { console.log(this); // Likely logs the window/global object });
So be careful mixing arrow functions with DOM events if you expect this
to refer to the element.
How this
behaves really come down to how the function is called , not how or where it's defined. Once you get familiar with these patterns, you'll start recognizing them in real code and avoid those tricky bugs.
Basically that's it.
The above is the detailed content of How does the 'this' keyword work 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
