JavaScript has encountered an Uncaught TypeError due to an illegal invocation

I am currently developing a lambda function that calls another function with specific parameters. While this code runs without issues in Firefox, it encounters an error in Chrome, displaying a strange message in the inspector:

Uncaught TypeError: Illegal invocation
. What could be causing this problem in my code?

var execute = function(func, args) {
    func(args);
}

execute(console.log, 'it will work!');

Answer β„–1

When using the console's log function, it is important that this refers to the console internally. The following code simulates a scenario where this may not be the case:

var x = {};
x.func = function(){
    if(this !== x){
        throw new TypeError('Illegal invocation');
    }
    console.log('Hi!');
};
// Works!
x.func();

var y = x.func;

// Throws error
y();

One way to ensure that this points to the console is by using the 'call' method as shown in the example below:

var make = function(callback,params){
    callback.call(console, params);
}

make(console.log,'it will be accepted!');

Alternatively, you can achieve the same result by using the 'bind' method as demonstrated in the code snippet below:

var make = function(callback,params){
    callback(params);
}

make(console.log.bind(console),'it will be accepted!');

Answer β„–2

If you're dealing with a function that requires 'this', you can create a new lambda function to encapsulate it and then use it as your callback.

function execute(callback, parameters) {
  callback(parameters);
}

execute(function(text){ console.log(text); }, 'This message will be displayed!');

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

Having trouble detecting the Selection event of a Dropdown List upon loading

When a user chooses an option from the dropdown menu, I need to capture the selected item and perform an action: $("#user-list").on("change", function() { var selectedUser = $(this).find(":selected").text(); // Perform action with the selected us ...

Executing a server-side Java function from client-side JavaScript or jQuery on a JSP page

My JSP file has a dropdown list where I can select different entity kinds. Upon selecting an entity kind, I want to populate another dropdown list with the field names associated with that entity kind. This requires calling a JavaScript function when chang ...

Learning to extract information from a JSON file with various key and value combinations

I am facing a challenge with my JSON data file, which contains UserIDs as keys and Passwords as values. My goal is to use JavaScript for validation by reading this JSON file. The structure of my JSON is as follows: IDsNPass = '[{"A":"A15"},{"B":"B15" ...

Exploring the β€˜ref’ feature in React alongside Material-UI

In my attempt to access input data through React's "ref" attribute on a TextField in Material-UI, I've encountered some difficulties. It doesn't seem straightforward to achieve this using the 'inputRef' or 'inputProps' me ...

Verify if the user is currently active

Is there a method to determine if the user is not active? I am currently utilizing raw PHP. I would like for the user to be automatically logged out once they close the window, indicating their inactivity. I attempted implementing window.addEventListener ...

Arranging arrangements in javascript

I am dealing with objects that contain the fields id and position. const items = [{id: 11, position: 1}, {id: 12, position: 2}, {id: 13, position: 3}, {id: 14, position: 4}, {id: 15, position: 5}, {id: 16, position: 6}]; These objects represent folders st ...

Capture all Fetch Api AJAX requests

Is there a way to intercept all AJAX requests using the Fetch API? In the past, we were able to do this with XMLHttpRequest by implementing code similar to the following: (function() { var origOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.p ...

Combining two sets of data into one powerful tool: ngx-charts for Angular 2

After successfully creating a component chart using ngx-charts in angular 2 and pulling data from data.ts, I am now looking to reuse the same component to display a second chart with a different data set (data2.ts). Is this even possible? Can someone guide ...

utilize ng-include in angularjs to include a page

For some reason, I am having trouble including a file using ng-include. The file is supposed to be included when a button is pressed: <button type="submit" class="btn btn-primary" ng-click="getPartial()">Compare</button> This is the function ...

Conceal a button using an AJAX POST request

I'm encountering an issue with my Ajax post where I am trying to disable the button used to submit data. I've reviewed my code and it seems accurate, but the button is not getting disabled. I attempted using $("#refreshButton").attr("disabled", t ...

What could be the reason for the failure of .simulate("mouseover") in a Jest / Enzyme test?

I have a scenario where a material-ui ListItem triggers the display of a material-ui Popper containing another ListItem on mouse over using the onMouseOver event. While this functionality works as expected, I am facing difficulties replicating the behavior ...

Creating a Delicious Earth Progress Pie

I'm looking to incorporate a unique progress bar design on my website, similar to this one: The progress pie Can anyone guide me on how to create a progress pie with an image inside it that changes color as it moves? ...

Adjusting the width of a div element using a button

I am currently diving into the world of JavaScript, React, and Node.js. My current challenge involves attempting to adjust the width of a div element using a button. However, I keep encountering the same frustrating error message stating "Cannot read prope ...

What causes the Vue.http configuration for vue-resource to be disregarded?

I am currently utilizing Vue.js 2.3.3, Vue Resource 1.3.3, and Vue Router 2.5.3 in my project while trying to configure Vue-Auth. Unfortunately, I keep encountering a console error message that reads auth.js?b7de:487 Error (@websanova/vue-auth): vue-resour ...

Connecting the mat-progress bar to a specific project ID in a mat-table

In my Job Execution screen, there is a list of Jobs along with their status displayed. I am looking to implement an Indeterminate mat-progress bar that will be visible when a Job is executing, and it should disappear once the job status changes to stop or ...

How should an iterable be sorted in React?

Let's break down the scenario using pseudo code: {this.props.myIterable.map((iterable) => { return ( <div>iterable.somevalue</div> ) }).sort((a,b) => {return b - a}) To clarify, I am iterating over certain props and displaying ...

Error code 405: The POST method is not compatible with submitting multiple forms using JavaScript code simultaneously

Having multiple forms on a single page that are all submitted using the same JavaScript code presents some challenges. <form class="form" id="cancelchallenge1" method="POST" action="{{action('ChallengeController@cancelChallenge')}}"> <i ...

Using a single Angular component to dynamically load data based on the query string

I am curious if it is feasible to load data based on a query string. For instance, when the user clicks on the following link http://localhost:4200/earning/customers?type=archived, the data will be loaded using the same component CustomersComponent. Simila ...

A Vue filtering feature that consistently adds 5 additional elements upon each use

I was wondering, how can I create a computed property filter function that always adds 5 more elements to the current array? Here are more details: Template: <span class="box-content" v-for="item in activeItems" :key="item.id"> <img class=" ...

Establishing numerous websocket connections within a singular application

I am looking to conduct load testing on our websocket service. Is there a method to establish multiple websocket connections from one workstation? My attempt with npm ws and websocket modules in conjunction with NodeJS was successful for a single connecti ...