The function is failing to provide a return value

In the Game.js file, there is a function that I am working on

Game.prototype.onClick = function(event){
     var x = event.x;
     var y = event.y;
     if (this.blueDeck[0].contains(x, y)) 
       alert("Blue Deck Clicked");
}

The OnClick function is called from a function in the Main.js file

canvas.addEventListener('mouseup', game.onClick, false);

Additionally, there is a function in Card.js

Card.prototype.contains = function(x, y){
    return true;
}

Despite setting everything up, the alert message does not appear.

Interestingly, when I remove the if statement in onClick, the alert is triggered. Other functions like

this.blueDeck[0].setDeckPos(w, h);
work perfectly fine in Game.js.

I am puzzled as to why contains is not returning true.

Answer №1

The verification validates my initial assumption. this will refer to the DOM element. The value of this is determined at runtime, meaning it depends on how the function is called, not where or how it was defined.

You have two options:

canvas.addEventListener('mouseup', function(event) {
    game.onClick(event);
}, false);

Alternatively, if you don't require access to the element, you can utilize .bind [MDN] (refer to this link for a polyfill for browsers lacking native support):

canvas.addEventListener('mouseup', game.onClick.bind(game), false);

Discover more about this:

Answer №2

An illustration of how the OP's concept operates demonstrates that the mistake is located elsewhere:

function Game(){
  this.blueDeck = [new Card()];
}

Game.prototype.onClick = function(event){
     var x;
     var y;
     if (this.blueDeck[0].contains(x, y)) 
       alert("Blue Deck Clicked");
}

function Card(){}

Card.prototype.contains = function(x, y){
    return true;
}

var g = new Game();
g.onClick(); // "Blue Deck Clicked"

Edit

When revising questions, it's important to clearly indicate the updates made. As seen in Felix's response, the method is not called by an instance of Game but by an event listener. It is crucial to remember that this is defined by the call.

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

AngularJS: Incorporate a loading spinner at the beginning of the document object model

After spending some time searching for the best way to accomplish this task without any luck, I am starting to doubt my search skills or perhaps no one has posed this question before. Despite leaning towards the former, I still find myself at a dead end. ...

A different component experiences an issue where Angular Promise is returning undefined

This is the carComponent.ts file containing the following method: async Download() { try { const settings = { kit: true, tyres: true, serviced: false, }; const [kits, tyres] = await Promise.all([ this.c ...

At what point does javascript cease execution on a webpage following a hyperlink being tapped?

I am curious about the behavior of JavaScript code, specifically related to the usage of setTimeout(). When a user clicks on a link to navigate to another page, I wonder at what point the JavaScript code on the current page stops running and the code calle ...

Steps for storing div content (image) on server

Currently in the process of developing a web application that allows users to crop images. The goal is for users to have the ability to email the URL so others can view the cropped image, ensuring that the URL remains active indefinitely by storing every c ...

Tips for retrieving the distance from the top of a specific div element and transferring it to another div

How can I add margin-top based on the tab that is clicked? Specifically, when TAB 4 is selected, I want the content to remain in the same position from the top. https://i.sstatic.net/ObDUg.jpg ...

Struggling to populate a nested array in a dropdown using AngularJS

I am currently working on populating JSON data into a dropdown list, specifically focusing on main category, sub category and sub sub category. Successfully managed to populate the main category and sub category, but facing challenges with populating subsu ...

Utilize a dynamic approach to add the active class to navigation list items

My files all have a header that includes a navigation bar. I am trying to use jQuery to add the 'active' class to the relevant list items (li). The method I initially thought of involved setting a variable on each page, assigning an ID equal to ...

I am currently using React to implement a feature that displays random facts for 5-second intervals. Despite no errors being displayed, the facts are not appearing on the page as expected

Client side My react application includes a section that is supposed to display random facts at 5-second intervals. Although no errors are displayed, the facts do not appear on the page when I run the code. import React from "react"; import &quo ...

What is the best way to choose all checkboxes identified by a two-dimensional array?

I need help with a question div setup that looks like this: <div class="Q"> <div id="Q1"><span>1. </span>Which of the following have the same meaning?</div> <div class="A"><input type="checkbox" id="Q1A1Correct" /& ...

What is the best way to display text from one text field onto another text field?

Here's a challenging question that I've been pondering... Issue: I am using a virtual keyboard that needs to interact with different text fields on various pages. Every time I click on a text field, the keyboard should appear, and every key I pr ...

I am looking to personalize a Material UI button within a class component using TypeScript in Material UI v4. Can you provide guidance on how to achieve this customization?

const styling = { base: { background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', border: 0, borderRadius: 3, boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', color: 'white', height: 48, ...

Analyzing data from a JSON API response for calculations

Can someone help me figure out how to add a percentage or number to each value in the total field of my code? I've tried multiple approaches but nothing seems to work. <?php $json=file_get_contents("http://www.upliftinghumanity.net/edd-api/sales/ ...

Troubleshooting: Issue with onclick event in vue.js/bootstrap - encountering error message "Variable updateDocument not found"

As a newcomer to frontend development, I have a basic understanding of HTML5, CSS, and Javascript. Recently, I started working on a vue.js project where I integrated bootstrap and axios. Everything seemed to be working fine until I encountered an issue whe ...

Verify if any choices are available before displaying the div block

I need to determine if there is a specific option selected in a dropdown menu, and then display a div if the option exists, otherwise hide it. I'm not just checking the currently selected option, but all available options. if (jQuery(".sd select opti ...

Tab buttons that switch between different sections with just a click

Forgive me if this seems like a simple coding issue, but I struggle with javascript and need some guidance... I have a setup where two buttons (blue and yellow) toggle between different content divs. On another part of the page, there are also two buttons ...

React Hooks: Issue with UseRef not detecting events from Material UI Select component

I'm currently utilizing React Hooks in my project. I am attempting to trigger an onclick event using the useRef hook. const component1: React.FC<Props> = props { const node =useRef<HTMLDivElement>(null); const ClickListe ...

Having trouble locating a method in $scope following angular $compile

Apologies for the simple question, I am a beginner in AngularJS and front-end development. I am attempting to create a modal using bootbox as shown below: In Service: function _modalData(){ let element = "<div onclick=\"saveSelecti ...

"Modify the MySQL database each time a user changes the value in a

As a student, I am looking to update value(s) whenever a student changes the value(s) in the correction or update form. So far, I have been able to retrieve and display values in text boxes based on the name selected from a dropdown list from the database ...

Is there a way for me to retrieve the locator value of a webelement?

How can I retrieve the selector value used in a selenium webelement in javascript? Let's say I have the following object: var el = browser.driver.findElement(by.id('testEl')); I want to extract the text 'testEl' from this object ...

What is the best way to access a DOM node within a withStyle component?

Currently, I am involved in a react project where my team and I are utilizing Material UI. I encountered a situation where I needed to access the DOM node of another component that was wrapped by a HOC. To achieve this, I attempted using ref in React but o ...