Access to "this" within an object literal is currently unattainable

I'm struggling to grasp how I can access a this that is located within one of the methods in an object literal that I have defined.

Let's take a look at an example:

var app = {
  click: function(e) {
    e.preventDefault();
    console.log('Clicked');
    this.saywhat();
  },

  saywhat: function() {  
    console.log('Say what ?');
  }
};

var link = document.querySelector('a');
link.addEventListener('click', app.click);

When I click on the link, I encounter the following error:

Uncaught TypeError: this.saywhat is not a function
. How can I ensure that saywhat() is accessible from within click()? (I am looking for a solution where I don't have to use app.saywhat())

Answer №1

The reason for this behavior is that the this keyword in event handlers refers to the element that triggered the event, such as the link in this case.

To address your situation, you have the option of using app.saywhat() or explicitly defining what this should refer to by utilizing Function.prototype.bind. For example:

link.addEventListener('click', app.click.bind(app));

Answer №2

Implement the use of .bind method.

button.addEventListener('click', handlerFunction.bind(handlerFunction));

See a live example here

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

Increase the totalAmount by adding the product each time

Can someone help me understand why the totalAmount shows as 20 when I add a product? Also, why doesn't it increase when I try to increment it? Any insights would be appreciated. Thank you. ts.file productList = [ { id: 1, name: 'Louis ...

Choosing Select2: Customizing the context of formatSelection

I've created a simple custom wrapper for Select2, which has been very helpful. However, I am facing an issue with the formatSelection field. When initializing Select2 through my wrapper, it looks like this: this.elem.select2({ allowClear : option ...

How can I modify the body background or background-color when navigating routes in Angular 4?

Is there a way to update the body background or background-color when changing routes in Angular 4? ...

I'm looking to add multiple markers with multiple info windows using the Google Maps API. How can I achieve this?

Having trouble with the Google Maps API v3? I've set up a map with custom markers, but when clicked they all display the same content in the info window. Can you take a look at my code and help me troubleshoot? Each marker is supposed to link to a spe ...

Is it possible to add values to an array of objects only if a certain condition is met

I am dealing with an array of objects structured like this [ { "monthlyData": [ { "dateYear": "2020-07", "data": [ { "id": "45bf4792-c5a5-44ed-b7e8-575 ...

Can an image map be utilized within an <a> element?

I am attempting to implement an image map within an <a> tag. It seems to be functioning correctly in Chrome, but I am encountering issues with it not working in Internet Explorer. Is it acceptable to use an image map in an <a> tag? Below is th ...

Looking for assistance in transferring information from one webpage to another dynamic webpage

I'm in the process of building a website to feature products using NextJs. My goal is to transfer data from one page to another dynamic page. The data I am working with consists of a json array of objects stored in a data folder within the project. Wh ...

Utilize Vue and webpack to seamlessly load images

Currently experimenting with the following: <img src="./src/assets/logo.png"></img> Or maybe this option: background-image: url("./src/assets/logo.png"); I have executed npm install [email protected] npm install file-loader --save-dev. ...

Using asynchronous functions in React Native still generates a promise despite the presence of the 'await' keyword

After making an API call, my react-native component is supposed to return some SVG. Despite using an async function with await, the function still returns a promise that has not resolved yet. I have seen similar questions asked before, but I am puzzled as ...

Instructions for capturing multi-dimensional arrays using forms in Vue

I have a snippet of code that looks like this: <div class="form-item"> <label for="list-0"><?php _e('List 0', 'test'); ?></label> <input name="list[0]" type="text" id="list-0" value=""> </div> &l ...

Exploring the functionality of the $.each jQuery iterator. Can someone clarify the distinctions between these two methods?

Having vertices as an array of google.maps.LatLng objects means that they should return latlng points. The first code snippet works perfectly fine, however, I encounter issues when using the second one. // Iterate over the vertices. for (var index =0; ind ...

Interactive jQuery slideshow showcasing top content

I'm experiencing an issue with displaying the initial content in a loop of divs that show their content sequentially after 5000 milliseconds. Is there a simple solution to make the first content area display immediately, followed by the rest sliding ...

Dynamically insert <td> elements into <tr> element using both jQuery and JavaScript

I am facing an issue with adding a new table data (td) element dynamically to the first table row (tr) in my JavaScript code. Here is the original table before adding the new td element: <table> <tbody> <tr> <t ...

One method of dirty checking using a shared service among controllers is effective, while the other method is not successful

As I was trying to solve the problem of sharing data between two separate controllers, I encountered a curious issue. Usually, I rely on services for this task and started creating a jsfiddle example, but unfortunately, I couldn't get it to function ...

Changing the image's flex-grow property will take precedence over the flex settings of other child

This is the error code I am encountering, where "text1" seems to be overridden <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <!--mobile friendly--> <meta name="view ...

Interacting between various components in separate files using React.js

Creating a page using React involves two Components with different functions. The first component, ProfileFill, is responsible for capturing form data. On the other hand, the second component, ProfileFillPercent, which resides in a separate file, calculate ...

What process does JavaScript use to interpret indexing?

function highlightRow(searchRow) { if(searchRow != null) { var oRows = document.getElementById('Table').getElementsByTagName('tr'); //use row number to highlight the correct HTML row ...

Exploring ways to seamlessly incorporate the Google Cloud Speech API into your website

As a beginner with the Google Cloud Platform, I am looking to incorporate the Google Speech API into my webpage using JavaScript. Despite researching documentation, I have been unable to find a solution. If anyone has knowledge on this topic, please help ...

Including jQuery in an Angular project generated with JHipster

I am facing a challenge with integrating jQuery into my Jhipster Angular project as a newcomer to Jhipster and Angular. My goal is to customize the theme and appearance of the default Jhipster application, so I obtained a theme that uses a combination of ...

Distinguishing a button based on its class

I am currently designing a website to showcase personalized store products. Each product info box includes a button, as shown in the screenshot below: https://i.sstatic.net/hiXiY.png Upon clicking on the "Options" button, users can view information about ...