JavaScript Default Binding Behavior ProblemIs there an issue with how default binding

Just finished reading an enlightening article on the FreeCodeCamp website all about the intricacies of the this keyword in JavaScript. I decided to test out some of the code snippets provided, but surprisingly enough, I ended up with completely different results.

function alerty() { 
  console.log(this.named + ' is calling'); 
}

const named = 'Kingsley'; 
alerty(); // Kingsley is calling'

  • alerty() seems to be displaying "undefined is calling" instead of the expected output of "Kingsley is calling" as outlined in the article.
  • I made sure not to include 'use strict'; in my code at any point.
  • What could possibly be causing this unexpected behavior?

Answer №1

As mentioned by Felix Kling in the discussion:

If you declare a local variable with const, it will not become a global object property.

Therefore, const name = 'Kingsley'; creates a local variable, whereas name = 'Kingsley'; will create a global object property (window.name = 'Kingsley';).

Given that on the global level, this refers to window, name = 'Kingsley'; will essentially set this.name in this specific scenario.

This explanation assumes that JavaScript modules are not being utilized.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leverage RTKQuery for retrieving data in segments

I've encountered an issue with my code that fetches data from an API. The response time is too long when retrieving all data, so I need to implement pagination to avoid timeouts. Here's the relevant section of my code: getDataWithDetails: builder ...

Tips for submitting an AJAX form in grails without relying on a traditional submit button

I am utilizing a g:formRemote tag to submit a form via ajax. <g:formRemote name="listAll" update="menuItemAJAX" url="[controller: 'superWaiter', action:'menuItem']" onSuccess="additionalContent()"> <a h ...

Utilizing socks5 authorization for individual connections and sending multiple requests with node.js

I possess access to a socks5 server including the host, port, username, and password. My aim is to authenticate myself and then initiate several requests to diverse servers through TCP using this socks5 proxy. How can I achieve this with node.js? While ex ...

Issues arising when using the "if" statement in mongoose search operations

When I search in MongoDB, I encounter validation issues. If it finds the information I am looking for, it returns the result. However, if it doesn't find anything, it returns an empty document. Here is my code and query in Postman: image exports.searc ...

Invoking a C# function inside a cshtml file

Having trouble calling a function in my CSHTML page. In the script of my CSHTML page : <script type="text/javascript" > //var sLoggedInUser = <%# GetSession_LoggedInIdUser() %>; $(document).ready(function () { ale ...

Combining two JavaScript objects with arrays

I am presented with the following data structure... array [ obj1 = {key1: a, key2: [a, b, c] }, obj2 = {key2: [c, d]} ]; My desired result is... array[ obj1 = {key1: a, key2: [a, b, c, d ...

Is it possible to attach a PDF file using just the PDF URL?

My current project involves an ionic application that performs calculations based on user inputs. Once the calculations are complete, the results are converted into a PDF using the generatePDF API call. Additionally, there is a requirement to email the gen ...

Using THREE.js to render an object only when it is in the foreground of another object

Is it feasible to render only the portion of Object 2 that hides Object 1? I am attempting to replicate the CanvasRenderingComposite destination-in effect in a 3D environment using THREEjs, essentially utilizing Object 1 as a mask. https://i.sstatic.net/ ...

Encountering an issue with loading the texture of a CG object while utilizing the GLTF

I’m facing an issue while loading a GLTF file into my React application. Although I successfully loaded the CG object (a dog!), I'm struggling to apply the texture. Does anyone have any suggestions on how to resolve this problem? I am currently usin ...

Retrieving multiple checkbox values from the front end using AJAX and passing them to

I have some code for ajax that is causing me issues. Here it is: var userCheckbox = $("input[name=chk]:checked").val(); This is the checkbox section in my html: <input id="checkbx" type="checkbox" name="chk" value="apple"/>apple</td> <inp ...

Moving a window in Pyqt5 using QtWebChannel

My goal is to enable the mousePressEvent and mouseMoveEvent events in order to move my app window using QtWebChannel. To achieve this, I am utilizing self.setWindowFlags(QtCore.Qt.FramelessWindowHint) to eliminate the default window flag and create a cust ...

Retrieving numerical values from strings using JavaScript

The text I have is formatted as follows: let str = "url(#123456)"; Within the given string, there is a number embedded in it. This number could appear anywhere in the string. I am looking to extract the number 123456 from the provided text. My current ...

Seeking a sleeker approach to composing various components with shared functions

Currently, I have a scenario where I have identical components that display data but also need to handle state manipulation and saving. There are 5 other similar components with slight differences in their functions. I am looking for a more efficient way t ...

Automatically send a form with Ajax when the page is loaded

I have a form that needs to be automatically submitted when the page loads. Here is my current jQuery code: <script> // wait for the DOM to be loaded $(document).ready(function() { document.getElementById('form1').submit( ...

Traversing an array of objects can result in an extraneous comma being displayed in the markup

View screenshot showing unwanted comma in output Hello there, I'm currently working on a gold shop website and dealing with an array of product objects. When mapping through this array to display products on the main page, I've encountered an is ...

I am looking to include a popover within my modal using Bootstrap version 3.0.2

Hey there, I'm having an issue where the popover that should be inside the modal is actually appearing outside of it in the top left corner, not visible within the modal itself. Below is my index code: <button type="button" id="example" class="bt ...

JSON data being sent through an AJAX request

Currently, I am developing a chat system that automatically refreshes using AJAX. Initially, I utilized the jQuery $.post function which worked fine for my needs. However, since I required JSON data from my PHP script, I switched to using the $.ajax functi ...

Validating CodeIgniter using advanced JavaScript techniques

When trying to insert data using a JavaScript and Bootstrap validation script, I encountered an issue. After entering a value in the text box, a warning pops up stating that the input value already exists. What should I modify in my script to address this ...

What is the best way to create an animated, step-by-step drawing of an SVG path

I am interested in creating an animated progressive drawing of a line using CSS with SVG/Canvas and JS. You can view the specific line I want to draw here <svg width="640" height="480" xmlns="http://www.w3.org/2000/svg"> <!-- Created with cust ...

tag-swapping function

I have a specific HTML code paragraph that I am working with: <p id=tag1> html statements before click </p> My goal is to create a function that will split the paragraph into two separate paragraphs like so : <p id=tag1> html statement ...