Surprising outcomes of call function usage in inherited classes

I am currently facing an issue while trying to create a new class that inherits from Function. Specifically, I am encountering difficulties when attempting to call the .call method on instances of this new class.

To illustrate, let's say I have defined the following constructor:

function myFunc() {
    Function.call(this);}

The prototype of myFunc is then set to be the same as Function:

myFunc.prototype = Function.prototype

Next, I create a new instance of this class:

var f = new myFunc()

When checking, it becomes evident that f.\__proto\__ equals Function.prototype:

f.__proto__ === Function.prototype /=> true

As expected, the Function.prototype includes a call method:

 Function.prototype.call /=> ƒ call() { [native code] }

However, calling f.call(null) results in an error:

f.call(null) /=> VM183:1 Uncaught TypeError: f.call is not a function
at <anonymous>:1:3

This situation raises the question of why f.call does not seem to check f.__proto__ for a call method even though it should logically do so.

Answer №1

Extending built-in classes has never been a simple task, especially not in the past.

The ability to effectively extend built-in classes is a feature introduced in ES6, which typically involves using ES6 syntax.

class MyClass extends SomeBuiltin {}

Using ES5 syntax usually leads to issues as it results in objects that do not properly implement internal functionalities, ultimately causing failures on methods and operations that rely on them (resulting in misleading call method errors).

If your JavaScript environment supports extending Function, this approach could work:

class myFunc extends Function {
    constructor() {
        super('return [...arguments]');
    }
}

const f = new myFunc();
console.log(f.call(null, 1, 2, 3)); // [1, 2, 3]

However, I would advise against extending Function altogether due to the need for code evaluation from a string, which can be unpleasant, potentially unsafe, and generally unnecessary.

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

"Customizing the Material-ui TextField DOM Element: A Step-by-Step

After trying the code below, I was expecting to see a yellowish "Hi," but instead received [object Object]. Is there a way to correct this issue? Possibly utilizing InputProps would help, but I haven't been able to locate a comprehensive tutorial on ...

Tips for efficiently storing and accessing data obtained from the "RESTBuilder" tool on the Total.js platform

After stumbling upon this informative tutorial on how to build a cryptocurrency comparison site with VueJs, I was inspired to create a single-page application using the total.js platform. My goal is to fetch the list of coins from the "coinmarketcap.com" A ...

Submitting form via ajax whenever triggered

I am looking for a way to submit each form individually by clicking on the submit button. My question: How can I send each form separately and display the results accordingly? The code I have tried does not seem to be working, as nothing is being sent and ...

Deliver an HTML code snippet with specific sections enclosed within HTML tags

I am in need of a custom function that has the ability to: Generate a string based on input from an array of strings Add appropriate HTML tags like <b> and <i> to specific index ranges Avoid unnecessary tags Ensure correct syntax For instanc ...

Modifying res.locals in Express.js updates the req object

I'm feeling a bit lost trying to understand what's going on here. I'm attempting to set a default profile picture in res.locals for a user if they don't already have one assigned. Here's the code I'm currently working with: / ...

ClickAwayListener doesn't function correctly when used in conjunction with Collapse or Fade animations

Currently, I am working on implementing a notifications area on my website. The idea is to display a notification icon, and once the user clicks on it, a list of notifications will be shown. For reference, you can view the code in this codesandbox I have ...

Tips for submitting data to the identical ejs view or partial following utilizing res.render get?

Is there a way to display data in my EJS file that is posted after the view has been rendered using res.render()? When I try to use <% date %> in my EJS file, it throws an error saying that date is not defined. This makes sense because the value is s ...

What is the best way to fake dependencies in Jest for each individual test?

Check out the complete minimal reproducible example Let's take a look at the app below: src/food.js const Food = { carbs: "rice", veg: "green beans", type: "dinner" }; export default Food; src/food.js import Food from "./food"; functio ...

Coordinating numerous AJAX requests in Angular with the help of Restangular

I am currently working on an Angular application that relies on $scope references to update the view using a factory singleton that exposes model and state objects. The challenge I face is ensuring that multiple AJAX calls (using Restangular) made by the f ...

Regain Identification or Data using PHP, JavaScript, and MySQL

I'm currently working on a project and I'm facing a challenge in retrieving Id either in php or js. I have 2 rows in the same table in mySql: row 1 = id_answer and row 2 = text. I am using a foreach loop in my code to extract the text from the ...

Using the variable (parameter) as a property in JavaScript

This function I'm creating will calculate the quantity of food data. const countFood = (foodType) => { let foodNeeded = 0; if (animal.food.type === foodType) { foodNeeded += +animal.food.amount; }; const food = foodType; if (foodN ...

What is the best way to retrieve the canonicalized minimum and maximum values within the beforeShow method of jQuery UI's datepicker?

I have a pair of datepicker elements that I want to function as a range. When a value is set in the "low" datepicker, it should adjust the minDate and yearRange in the other datepicker, and vice versa with the "high" datepicker. The challenge I'm faci ...

Every time I employ window.location, the Iframe becomes nested

I am experiencing an issue with my HTML structure: <html> <body> This is the container of the iframe <iframe src="/foo.html"> </iframe> </body> </html> (/foo.html) <html> <script type="text/javascript"> $( ...

How can you determine when a download using NodeJS HTTPS.get is complete?

Currently, I am facing an issue while downloading a file. My goal is to perform an action immediately after the download is complete. Specifically, I aim to import a .js file as soon as it finishes downloading. var request = https.get('https://m ...

What could be causing my Django Slick-Slider carousel to malfunction?

I have encountered numerous posts discussing the same issue, but unfortunately, none of them offered a solution that worked for me. The slick-slider folder is properly stored in my static files and is being accessed correctly, yet no changes are reflected ...

Creating a randomized number within the nested click event's inner function

One of the challenges I'm facing is trying to generate a single random number within a nested event click function. Unfortunately, when running the code, instead of getting a single number, I end up with multiple random numbers being output. The spec ...

Instructions on replicating the content from one div to another div

Is there a way to exhibit the modified content of div (container1) in another div (container2)? <div id="container1"> <div id="slide1"> Here, you will find various elements such as input boxes, select dropdowns, and plain text. </div& ...

Tips for changing the focus between various modals and HTML pages after minimizing a modal with jQuery

I have been utilizing a plugin from to minimize a bootstrap modal within my angular application. The problem I am facing with this plugin is that whenever I minimize a modal, I am unable to interact with the html page, such as typing in input boxes or sc ...

Methods for transferring data to controller in Angular Modal service

After implementing the angular modal service discussed in this article: app.service('modalService', ['$modal', function ($modal) { var modalDefaults = { backdrop: true, keyboard: true, m ...

Troubleshooting jQuery Dropdown Menu Animation Bugs

Take a look at this interesting fiddle: https://jsfiddle.net/willbeeler/tfm8ohmw/ HTML: <a href="#" class="roll-btn">Press me! Roll me down and up again!</a> <ul class="roll-btns"> <li><a href="#" class="control animated noshow ...