Unable to access Function.prototype.call directly

function testFunc(b) { return b }

testFunc(2) // => 2

testFunc.call(null, 2) // => 2

Function.prototype.call(testFunc, null, 2) // => undefined

Curious why the final line returns undefined, aren't they supposed to be equivalent?

Answer №1

In these instances, the results will be consistent:

function f(a) { return a}

console.log(f(1)); // => 1

console.log(f.call(null, 1)); // => 1

console.log(Function.prototype.call.call(f, null, 1)); // => 1

It's important to note the added usage of.call in the final statement.

Now, let's delve into the rationale behind it:

Function.prototype.call

As per the specification, Function.prototype.call executes an abstract operation Call(func, thisArg, argList).

Therefore, f.call(null, 1) triggers the abstract operation Call(f, null, 1), with f representing the function being executed, null as the calling context, and 1 as the argument passed to f. This leads to the anticipated output.

Based on this logic, applying

Function.prototype.call(f, null, 1)
would yield the abstract operation Call(Function.prototype, f, null, 1), where Function.prototype is the invoked function, f acts as the context, and null and 1 serve as arguments for Function.prototype. Obviously, this won't work as intended.

Function.prototype.call.call

However, by employing

Function.prototype.call.call(f, null, 1)
, you invoke the abstract call operation Call(Function.prototype.call, f, null, 1). In this case, Function.prototype.call serves as the target function, f takes on the role of the calling context, while null and 1 are provided as arguments. Consequently, the outcome mirrors that of: f.call(null, 1).

Answer №2

Let's dive into the following example:

function fn() { console.log(this); }
fn.a = function(){console.log(this)}
fn.a() // function fn() { console.log(this); }

Now, let's explore creating a custom call function:

  Function.prototype.customCall = function () {
    let arr = Array.prototype.slice.call(arguments, 1);
    this.apply(arguments[0], arr);
  }

  function a(ar){ console.log(ar + this.name) };
  let obj = {name : "thierry"};
 // a.customCall( obj, 'hi ')

Function.customCall.customCall(a, obj, 'hi ');

When we execute

Function.prototype.customCall.customCall(a, obj, 'hi ')

Initially, on the first run we have:

  1. arr = [ obj, 'hi ']
  2. this = Function.customCall

resulting in

Function.customCall.apply(a, [ obj, 'hi ']);

Then, on the second run:

  1. arr = ['hi']
  2. this = a

leading to a.apply(obj, ['hi']), equivalent to a.call(obj, 'hi');

If we were to use

Function.customCall(a, obj, 'hi ');
, the initial run would result in this = Function which will not work and throw an error or return undefined. This can be handled with a try-catch.

  Function.prototype.customCall = function () {
    let arr = Array.prototype.slice.call(arguments, 1);
    try{
       return this.apply(arguments[0], arr);
    }catch(e){}
  }

  function a(ar){ return ar + this.name };
  let obj = {name : "thierry"};
  console.log(Function.customCall(a, obj, 'hi ')); // undefined

  console.log(Function.customCall.customCall(a, obj, 'hi ')); // hi thierry

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

Automatic Incremental Counter

Currently in the process of building a website and I need the number on the homepage to gradually increase from 1 onwards. After searching through various websites, I have yet to find a solution. I am hoping to locate the code necessary for incorporating ...

"Centered in the middle of the screen, an animated

Encountering an issue with this code on Chrome. Clicking on the checkbox causes the text/checkbox to shift in position/padding/margin unexpectedly.. :( View the code on JSFiddle HTML <input id="inp" type="checkbox" /> <div id="cb" class="inp_ch ...

`How to prevent other events from triggering in jQuery while an animation is running`

Writing again to seek help with a script issue on my webpage. I previously posted about a problem with the menu focus a week or two ago on this forum. A user suggested a helpful script, but unfortunately, it has a bug that I can't seem to fix. I' ...

Ability to utilize an alternative attribute type within a TypeScript object

Within my class, I have: class Target { ... readonly overlay: { type: 'none' } | { type: 'centering', style?: { color?: string, offset?: number, size?: number, } } | { type: 'enterin ...

Hierarchical Navigation Panels

I am currently facing a challenge with designing a highly intricate navigation menu. The menu is structured in 3 levels with 2 parent tabs. Upon hovering over any tab, the user should be able to view its corresponding child navigation levels, and when not ...

Unable to generate onsen-ui popover

My expertise lies in utilizing the Monaca platform for developing mobile applications using Onsen UI and AngularJS. I am looking to incorporate a popover feature from Onsen into my app, and have tried the following code snippet: angular.module('app& ...

Is there a way to identify which specific item in a watched array has been altered in VueJS?

Imagine having an array declared in the data section like this: data() { return { myData : [{foo:2, bar:3},{foo:4,bar:5}] } } If you want to identify when the bar property of the second element changes, what should your watch function look li ...

Retrieve the appended element's object

I am currently facing an issue with accessing elements that are automatically added by a library in my code. In my HTML, I have the following line: <div class="bonds" id="original" style="display:block;"></div> The library appends some elemen ...

Error message: "The variable _ is not defined when trying to use angular-google-maps library"

I'm encountering an issue where I'm receiving a ReferenceError: _ is not defined while using the angular-google-maps I'm puzzled as to why this error is occurring, as I believe I am following the instructions provided on the website. I hav ...

Tips for modifying style.display using JavaScript

On my website, the menu is structured like this: <nav id="menu"> <label for="tm" id="toggle-menu">Menu <span class="drop-icon">▾</span></label> <input type="checkbo ...

Encountered an error: The function run is not supported for the current bot command

Recently, I attempted to create a command handler in discord.js and encountered an issue when running the bot. A TypeError was thrown: TypeError: bot.commands.get(...).run is not a function The error occurs towards the end of the code snippet below. bot ...

Tips for delivering a heartfelt message when a user adds an item

import React from 'react'; import { useForm } from "react-hook-form"; import { toast } from 'react-toastify'; const AddStorage = () => { const { register, handleSubmit } = useForm(); const submitData = data => ...

There are no markers or popups currently displayed on the map

Utilizing the ngx-leaflet plugin for leaflet, I have established the base layers and integrated a listener for the leafletMapReady event. Within my handler, I attempted to add both a marker and a customized popup. The handler code is displayed below: init ...

What is the method used by three.js to render video with spherical UV mapping?

I have a streaming video displayed in a 3*3 format. I am able to splice the entire video into individual sections using THREE, // Creating a 3x3 PlaneGeometry var geometry = new THREE.PlaneGeometry(400, 200, 3, 3); const video1 = document.getElem ...

Here's how to use the useState hook directly in your React components without

Currently, I am using the code snippet below to import useState: import * as React from 'react' import {useState} from 'react' I wanted to see if there is a way to condense this into one line, so I attempted the following: import * a ...

Unable to get Discord.js sample code functioning correctly

Despite my best efforts, I can't seem to figure out why this simple example code is not working. As a newcomer to Java Script, I am struggling with understanding why the line GatewayIntentBits.Guilds is causing an error. Surprisingly, when I comment o ...

Preventing Unauthorized Access: Redirecting to Login Page in Vue.js

Here is the code snippet I'm working with: <script> export default{ props:['idStore'], methods:{ addFavoriteStore(event){ $(function () { $(document).ajaxError(functi ...

Is it possible to create a webpage where the header and footer remain static, while the content in the body can be dynamically changed

I am in the process of creating a webpage where main.html will load a page with a static header and footer that remains unchanged when navigation links are clicked. I'd like to achieve this using Javascript, with the body content being sourced from an ...

Retrieving the value of a duplicated button in AngularJS

I have implemented a basic HTML table using AngularJS to display data for each item in my "names" array. Each item represents an object with various attributes such as Name, id, etc. Along with each row in the table, I have included a button. However, I am ...

What is the best way to exchange configuration data among Javascript, Python, and CSS within my Django application?

How can I efficiently configure Javascript, Django templates, Python code, and CSS that all rely on the same data? For example, let's say I have a browser-side entry widget written in Javascript that interacts with an embedded Java app. Once the user ...