国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Web Front-end JS Tutorial this keyword in javascript

this keyword in javascript

Jan 12, 2025 pm 02:40 PM

this keyword in javascript

One of the most confused keyword in JavaScript is the this keyword. It's a special identifier keyword that's automatically defined in the scope of every function, but what exactly it refers to confuse even seasoned JavaScript developers.

The this keyword refers to the context where a piece of code, such as a function's body, is supposed to run. Most typically, it is used in object methods, where this refers to the object that the method is attached to, thus allowing the same method to be reused on different objects.

The value of this can be identified where the function is executed not where the function is declared

We will examine different rules to identify the this in javascript

Default binding

The default rule we will apply most common case of function calls: standalone function execution. Think of this this rule as the default catch-all rule when none of the other rules apply.

In standalone functions call this value will be globalObject (in browser env it is window object, in node env it will be global)

function bar() {
    console.log(this) // this will be global object (window)
}
bar()

But......

the value of this can be different how the code is running in strict mode or non strict mode

If When function invoked as standalone function this typically refer to global object in non strict mode and undefined in strict mode

"use strict"
function bar() {
    console.log(this) // undefined
}
bar()

Subtle but important, the global object is only eligible for the default binding if the contents of bar() are not running in strict mode;

function bar() {
    console.log(this) // global object (window)
}
(function() {
    "use strict"
    bar()
})()

Implicit binding

When a regular function is invoked as a method of an object (obj.method()), this points to that object.

function bar() {
    console.log(this)
}
const obj = {
    name: "javascript",
    foo
}
obj.foo() // this here is object owing the function

Firstly, notice the manner in which bar() is declared and then later added as a reference property onto obj. Regardless of whether foo() is initially declared on obj, or is added as a reference later (as this snippet shows), in neither case is the function really "owned" or "contained" by the obj object.

Implicit lost:
When using callbacks, implicitly bound function loses that binding, which usually means it falls back to the default binding, of either the global object or undefined, depending on strict mode.

function bar() {
    setTimeout(function() {
        console.log(this) // this will be global object
    }, 1000);
}
const obj = {
    name: "javascript",
    bar
}
obj.bar() // this will be global object
function bar() {
    console.log(this)
}
const obj = {
    name: "javascript",
    bar
}
const a = obj.bar
a() // this will be global object

Explicit binding

With implicit binding as we just saw, we had to mutate the object in question to include a reference on itself to the function, and use this property function reference to indirectly (implicitly) bind this to the object.

But, what if you want to force a function call to use a particular object for the this binding, without putting a property function reference on the object?

Yes its possible, javascript provide many methods like .map, .filter for array we have few methods in function. These are apply , call and bind

Here is the syntax for these methods
call

function bar() {
    console.log(this) // this will be global object (window)
}
bar()

apply

"use strict"
function bar() {
    console.log(this) // undefined
}
bar()

Subtle different between apply and call. The syntax is same but we pass arguments as array in apply method

function bar() {
    console.log(this) // global object (window)
}
(function() {
    "use strict"
    bar()
})()

Invoking bar with explicit binding by bar.call(..) allows us to force its this to be obj.

new Binding

When a function is used as a constructor (with the new keyword), its this is bound to the new object being constructed, no matter which object the constructor function is accessed on. The value of this becomes the value of the new expression unless the constructor returns another non–primitive value.

function bar() {
    console.log(this)
}
const obj = {
    name: "javascript",
    foo
}
obj.foo() // this here is object owing the function

The above is the detailed content of this keyword in javascript. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

RimWorld Odyssey How to Fish
1 months ago By Jack chen
Can I have two Alipay accounts?
1 months ago By 下次還敢
Beginner's Guide to RimWorld: Odyssey
4 weeks ago By Jack chen
PHP Variable Scope Explained
3 weeks ago By 百草

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)

Hot Topics

PHP Tutorial
1506
276
How to make an HTTP request in Node.js? How to make an HTTP request in Node.js? Jul 13, 2025 am 02:18 AM

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

How to Check if an Array Includes a Value in JavaScript How to Check if an Array Includes a Value in JavaScript Jul 13, 2025 am 02:16 AM

In JavaScript, check whether an array contains a certain value. The most common method is include(), which returns a boolean value and the syntax is array.includes(valueToFind), for example fruits.includes('banana') returns true; if it needs to be compatible with the old environment, use indexOf(), such as numbers.indexOf(20)!==-1 returns true; for objects or complex data, some() method should be used for in-depth comparison, such as users.some(user=>user.id===1) returns true.

Advanced JavaScript Scopes and Contexts Advanced JavaScript Scopes and Contexts Jul 24, 2025 am 12:42 AM

The scope of JavaScript determines the accessibility scope of variables, which are divided into global, function and block-level scope; the context determines the direction of this and depends on the function call method. 1. Scopes include global scope (accessible anywhere), function scope (only valid within the function), and block-level scope (let and const are valid within {}). 2. The execution context contains the variable object, scope chain and the values of this. This points to global or undefined in the ordinary function, the method call points to the call object, the constructor points to the new object, and can also be explicitly specified by call/apply/bind. 3. Closure refers to functions accessing and remembering external scope variables. They are often used for encapsulation and cache, but may cause

How to Get the Value of an Input Field in JavaScript How to Get the Value of an Input Field in JavaScript Jul 15, 2025 am 03:09 AM

To get the value of the HTML input box, the core is to find the corresponding element through the DOM operation and read the value attribute. 1. Use document.getElementById to be the most direct way. After adding an id to input, you can get the element and read the value through this method; 2. Use querySelector to be more flexible, and you can select elements based on attributes such as name, class, type, etc.; 3. You can add input or change event listeners to achieve interactive functions, such as obtaining input content in real time; 4. Pay attention to the script execution timing, spelling errors and null judgment, and ensure that the element exists before accessing the value.

JavaScript Template Literals: Syntax and Use Cases JavaScript Template Literals: Syntax and Use Cases Jul 13, 2025 am 02:28 AM

Template strings are a feature introduced in JavaScriptES6, which wraps content with backticks and supports variable interpolation and multi-line strings. 1. Use backticks to define strings such as Thisisatemplateliteral; 2. Insert variables or expressions through ${} syntax such as Iam${age}yearsold.; 3. Naturally support multi-line text without manually adding newlines. Common scenarios include dynamically generating HTML content, multi-line string output, and simplified conditional logical stitching. Notes include avoiding injection attacks, advanced usage of tag templates, and keeping logic simple.

How to get the value of a selected radio button with JS? How to get the value of a selected radio button with JS? Jul 18, 2025 am 04:17 AM

There are two core methods to get the selected radio button value. 1. Use querySelector to directly obtain the selected item, and use the input[name="your-radio-name"]:checked selector to obtain the selected element and read its value attribute. It is suitable for modern browsers and has concise code; 2. Use document.getElementsByName to traverse and find the first checked radio through loop NodeList and get its value, which is suitable for scenarios that are compatible with old browsers or require manual control of the process; in addition, you need to pay attention to the spelling of the name attribute, handling unselected situations, and dynamic loading of content

Building Secure Sandboxed Iframes with JavaScript Building Secure Sandboxed Iframes with JavaScript Jul 16, 2025 am 02:33 AM

To use JavaScript to create a secure sandbox iframe, first use the sandbox attribute of HTML to limit iframe behavior, such as prohibiting script execution, pop-up windows and form submission; secondly, by adding specific tokens such as allow-scripts to relax permissions as needed; then combine postMessage() to achieve secure cross-domain communication, while strictly verifying message sources and data; finally avoid common configuration errors, such as not verifying the source, not setting up CSP, etc., and perform security testing before going online.

See all articles