In JavaScript, the "this" keyword points to a different object

Here is a script that needs attention:

Bla = function() {
  this.prop = 123;
}
Bla.prototype.yay = function() {
  console.log(this,this.prop);
}
X = new Bla();

$(document).ready(X.yay); // output: #document undefined --> why?
$(document).ready(function(){
  X.yay(); // output: Bla 123 --> desired result
});

What can be done to ensure that the first call functions correctly (with 'this' referring to X) without extending Object?

Answer №1

Simply put, the context of a function's this keyword depends on whether it is part of an object or not.

When a method is passed into a function, it loses its association with any object and becomes a local variable within that function. In such cases, this typically refers to the document object, as seen in events like document ready.

In modern JavaScript, you have the option to bind a method to a specific object.

For example:

$(document).ready(X.yay.bind(X));

Note that support for this feature may vary across different browsers, so using an anonymous function could be a more compatible alternative, especially for older versions of Internet Explorer.

Answer №2

Utilize the bind function:

$(document).ready(Y.hooray.bind(Y));

By using this method, a "wrapper" is generated around the function that assigns this to Y upon invocation.

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

I encountered an issue while making customizations to my default next.config.js file. Despite attempting various solutions, I consistently encountered an error regarding the invalid src property

I'm currently trying to introduce some custom configurations into the next.config.js file. However, I keep encountering an error regarding an invalid src prop. Despite my attempts to troubleshoot in various ways, the error persists. // ...

Grunt is throwing an error message of "Cannot GET/", and unfortunately ModRewrite is not functioning properly

I've recently started using Grunt (just began last Friday). Whenever I run Grunt Serve, it displays a page with the message "cannot GET/" on it. I tried implementing the ModRewrite fix but the error persists. Any assistance would be highly appreciat ...

Dealing with performance issues in React Recharts when rendering a large amount of data

My Recharts use case involves rendering over 20,000 data points, which is causing a blocking render: https://codesandbox.io/s/recharts-render-blocking-2k1eh?file=/src/App.tsx (Check out the CodeSandbox with a small pulse animation to visualize the blocki ...

Combining text output using JavaScript, HTML, and Vue

Can you help solve this challenge of outputting concatenated text from a javascript code? The script in question draws a quarter circle that is proportional to the size of the bar and showcases the value of pi accurate to three decimal places. To display ...

Error: The property 'match' is undefined and cannot be read by Object.j during rendering in angular-datatables.min.js at line 6

I am currently using angular-datatables.min.js for my data table, but I have encountered an error that I have been unable to resolve. Is there anyone who can provide assistance with this issue? App.controller('DailyTaskListController', ['$s ...

Struggled to Find a Solution for Code Alignment

Is there a tool or software that can align different types of codes with just one click? I've tried using the Code alignment plugin in Notepad++, but it hasn't been effective. For example, when aligning HTML code using tags, I couldn't find ...

What is the reason for the failure of multiple place markers on a planet object3D?

After spending hours trying to debug a piece of code I wrote 3 years ago using Three.js, I still can't figure out why it's not working anymore. I thought updating all the other code to use ES6 for Three.js would solve the issue, but when I try t ...

Tips for dynamically coloring table cells in Spotfire based on their values

Creating Dynamic Table with HTML After successfully creating a cross table in Spotfire, I now aim to replicate the same table in HTML within a text area. I managed to add values using calculated values, but I'm stuck on how to dynamically set the bac ...

The tab component is failing to load due to an issue with the Bootstrap tab

I've created a page displaying different locations with two tabs - one for Google Maps and another for weather. For example, take a look at this location: The issue I'm facing is that when switching between the tabs, they don't load fully. ...

Utilizing ES6 default arguments for managing empty strings

Here is a simple key-value map of colors based on types: const COLORS_BY_TYPE = { RED: 'red', BLUE: 'blue', GREEN: 'green', }; const getCorrectColor = ({ colorType = 'GREEN' }) => COLORS_BY_TYPE[colorType. ...

Rearrange Material UI styles in a separate file within a React project

Currently, I am developing an application utilizing material-ui, React, and Typescript. The conventional code for <Grid> looks like this: <Grid container direction="row" justifyContent="center" alignItems="center&q ...

Issue with Material-UI tab when using a datatable within it's content

I implemented the Simple Tabs feature from Material-UI with a Tab containing a Datatable using React-Data_Table. However, I noticed that this particular tab is not responsive like the others when the table is full. Empty Full Here's a snippet of th ...

Flask and the steps to modify CORS header

While working on my localhost, I came across a CORS error when building an application to handle search queries for a different domain. The specific error was: "Cross Origin Request Blocked... (Reason: CORS header 'Access-Control-Allow-Origin' mi ...

Leveraging npm in vanilla JavaScript applications

Because of limitations set by the governance of my current project, I am unable to utilize many of the modern JS libraries and frameworks. Therefore, for our MVP, we are resorting to using vanilla JS directly loaded to the client (un-minified), which is no ...

Extract the price value from the span element, then multiply it by a certain number before adding it to a div element

On the checkout page of my website, I have the following HTML: <tr class="order-total"> <th>Total</th> <td><strong><span class="woocommerce-Price-amount amount"> <span class="w ...

Enhancing ASP.NET MVC 5 Application with jQuery Validate: Implementing Submit Button Click Events

In the process of developing an ASP.NET MVC 5 application, I find myself faced with a dilemma. The current setup involves using the jQuery Validate plug-in that comes packaged with MVC applications. Upon clicking the "submit" button, jQuery Validate kicks ...

Retrieving JSON Arrays in PHP through an AJAX Request

Having trouble extracting data from multiple arrays in an AJAX request. Can anyone help? Here's what I'm trying to send: https://i.stack.imgur.com/4MEL4.png Executing a jQuery AJAX POST to a PHP file, but uncertain how to retrieve the data. An ...

When an item in the accordion is clicked, the modal's left side scroll bar automatically scrolls to the top. Is there a solution to prevent this behavior and

When I first load the page and click on the Sales accordion, then proceed to click on Total reported and forecasted sales, the scrollbar jumps back up to the top The marked ng-container is specifically for the UI of Total reported and forecasted sales He ...

Steps to include a border around text and center align it:

As a beginner in Html and CSS, I am trying to create a heading with the text "Women safety" and wrap it with a border. However, when I apply the border to the text, it covers the entire width, extending both left and right. I only want the border to be a ...

How to trigger a file download instead of opening it in a new tab when clicking on a txt or png file in AngularJS

After retrieving my file URL from the backend API, I am trying to enable downloading when the user clicks a button. Currently, the download function works smoothly for Excel files (`.xlsx`), but for text (`.txt`) files or images (`.jpeg`, `.png`), it only ...