The object variable is not recognized by the Javascript method

var Geometry = function(shapeType)
{
    this.shapeType = shapeType;

    addEventListener("resize", this.adjust);
}

Geometry.prototype.adjust = function()
{
    alert(this.shapeType);
}

.

var figure = new Geometry('rectangle');

After resizing, I expect to see an alert with the word rectangle, but it currently shows undefined

Answer №1

It is important to pass the scope in order to utilize this within the resize event.

var Figure = function(shape) {
  this.shape = shape;
  addEventListener("resize", this.adjust.bind(this));
}

Figure.prototype.adjust = function() {
  alert(this.shape);
}

var obj = new Figure('square');

Answer №2

To achieve the desired outcome of an alert displaying 'rectangle', make sure to utilize variable.align(). This method is necessary when generating a new object.

Answer №3

The value of the keyword this is determined by how a function is called. It cannot be directly assigned during execution, and it may vary each time the function is invoked. In ES5, the bind method was introduced to explicitly set the value of a function's this irrespective of its invocation context [MDN]

Function.prototype.bind() creates a new function that binds its this keyword to a specified value when called.

var Shape = function(type) {
  this.type = type;
  addEventListener("resize", function() {
    this.align();
  }.bind(this));
  //OR addEventListener("resize", this.align.bind(this));  
}

Shape.prototype.align = function() {
  alert(this.type);
}


var variable = new Shape('rectangle');

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

Vue: The function "priceFilter" is not defined in this context

function sanitizeInput(event) { event.target.value = event.target.value.replace(/[^\d.]/g, ""); event.target.value = event.target.value.replace(/^\./g, ""); event.target.value = event.target.value.replace(/\.{2,}/g, "."); event.targe ...

Tips for maintaining video playback in HTML5 when the video element is clicked

I am currently working on creating a straightforward video conference setup and I specifically want to only allow the fullscreen feature when sharing the video element. I also want to disable all other controls such as volume, mute, seek, play, pause, and ...

React Component not retaining its value

I am currently facing an issue with a React component where I need to read a file from an Upload and pass the contents onto a child component for display. Although I can successfully read the file contents using FileReader and see the results in the cons ...

To achieve this, my goal is to have the reels start playing on a separate page when a user clicks on the designated image. I am currently working on a project that involves this

When a user clicks on the designated image, I want the reels to start playing on a separate page. In my main project, I have a reels project within it, with the reels project built in ReactJS and the main project in React TypeScript. For example, if a user ...

Creating a Full Page Background Image That Fits Perfectly Without Resizing or Cropping

Can someone help me achieve the same effect as the website linked below, where the background image fades instead of being a slideshow? The image should be 100% in width and height without any cropping. I have managed to set this up with the codes provided ...

Leveraging GSAP and Vue by utilizing props to dynamically calculate a maxWidth

I am working on animating buttons in my application using GSAP. The idea is that when a user clicks the button, it should animate the maxWidth of the button. I want this to be dynamic by adding a percentage of the max width set using props. Is it possibl ...

Tips for utilizing field mapping for a nested item in TypeScript

I am working with two separate objects below, let response = { offer: { custom_fields: { job_title: 'engineer' }, starts_at: 'test', ...

Using a combination of radio buttons and JavaScript to adjust the color of a div element

Currently, I am experimenting with radio buttons to modify the background color of my div tag. My goal is to incorporate more than one condition. For example, if button A and button B are both clicked, then change the color to green. This is what I have im ...

The Less compiler (lessc) encounters an issue on a fresh operating system. ([TypeError: undefined is not a function])

After setting up my new development environment on Windows 10, I encountered an issue with less. Following the instructions on lesscss.org, I installed less using: npm install -g less The installation process completed without any errors. However, when ...

When running the `npm run dev` command, Tailwind does not seem to function

I have been given a task to create forms using tailwindcss, but when I try to run `npm run build`, it doesn't work. Can anyone assist me with this? npm ERR! code ELIFECYCLE npm ERR! errno 9 npm ERR! <a href="/cdn-cgi/l/email-protection" class="__cf ...

Verify whether a web application is equipped with React, Angular, or Vue

Is there an easy way to identify the client-side libraries used by an application if they are minified or compressed? While examining all the JavaScript sent from the server to the client, it can be challenging to determine if one of the top three popular ...

Showing data in json format using Angular

I have designed a data table that showcases a list of individuals along with their information. However, when I click on the datatable, it keeps opening a chat box displaying the details of the last person clicked, overriding all other chat boxes. 1. Is t ...

Angular: handling asynchronous errors when no promise is utilized within a subscription

I am currently working with a material design table and have created custom functions to load the data and extract objects from a JSON array object. Here is a snippet of the code I am using: public getDocumentList() { return this.http.get(this.getDocu ...

Ways to update the contents of an individual div within an ng-repeat loop

I am currently working on some Angular code. <div ng-repeat="item in items | filter:search" class="container"> <h3>{{item.name}}</h3> <p>category:{{item.category}}</p> <p>price:INR {{ ...

Show fixed div at specific height

Is there a way to have a fixed title in a DIV that only displays once the user scrolls to the relevant section on the website? I'm looking for a solution where the DIV is hidden until the section is reached during scrolling. ...

Sorting elements in jQuery UI by connecting them together

I'm faced with a challenge where I have two columns containing multiple rows/divs each. My goal is to use jQuery UI Sortable in such a way that when I drag a div in the left column, the corresponding row/div in the right column will also be sorted acc ...

An issue with Azure App Service causing extra slashes in URLs

I am currently developing a node.js application that is being deployed on Azure App Service. On my local machine, the application functions perfectly at: http://localhost:55231/search?q=pink+floyd However, when deployed on Azure, the URL behaves strange ...

Tips for identifying MIME type errors in an Angular 9 application and receiving alerts

While working on my Angular app, I encountered the MIME type error Failed to load module script: The server responded with a non-javascript mime type of text/html. Fortunately, I was able to resolve it. Now, I'm stuck trying to figure out how to rece ...

The Increment of DOM Event Detail Stays Unchanged When Angular Click Event is Triggered

Attempting to detect a triple click or touch event in an Angular 7 application. Code snippet from the template: <img id="logoImage" src="/assets/logo.png" (click)="clickLogo($event)"> Code snippet from the component: clickLogo(event) { console ...

Populating a dropdown with a list by utilizing the append grid library

Hey there! I'm currently using the jquery appendGrid plugin to display a drop-down menu in one of the columns. In the code snippet below, the column labeled "Origin" has a drop-down option that is working as expected. $(function () { // Initializ ...