Identifying if a function is within the prototype chain of a class instance in ES6

Consider the following ES6 class:

class C {
  x () { }
  fnIsMethodOfC (fn) { return /* ? */ }
}

Along with various functions like

function y () {}
z = () => {}

What is an efficient way to determine if a function is a method of C, for example:

c = new C()
c.fnIsMethodOfC(c.x) === true
c.fnIsMethodOfC(C.prototype.x) === true
c.fnIsMethodOfC(y) === false
c.fnIsMethodOfC(z) === false

While one could potentially recursively search through the prototype chain, it may not be the most optimal solution.

Explore related questions here:

  • JavaScript ES6: Test for arrow function, built-in function, regular function?
  • Determine if a JavaScript function is a bound function
  • ES6 Iterate over class methods

Answer №1

Perhaps a potential solution could be:

function checkIfMethodBelongsToClass(method, className) {
  const prototype = Object.getPrototypeOf(className)
  return prototype && prototype[method.name] === method
}

Answer №2

function checkMethod(fn) {
  if(!fn || !fn.name) return false;
  return !!this[fn.name] && fn !== this[fn.name];
}

In addition to that, this function will also perform an additional check to see if the actual function is different.

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

What is the best way in jQuery to show each element of an array one at a time with a space in an input field?

I have a large array filled with strings that I want to display one by one in a text field, automatically concatenated with a space bar. Below is my code: <script> x = 0; function abc() { for (i = 0; i < words[x].length; i++) { ...

`python regular expressions function malfunctioning``

I am currently learning Python, and even though this might seem like a basic question to many of you, I am seeking some guidance in figuring out what is causing the issue here. My aim is to develop a function that can scan a text for phone numbers. i ...

The performance of my JavaScript function seems to be lagging

I'm currently gathering extensive data from an API using an async function that iterates through a large amount of information using a loop. I'm sending about 100 requests and it's taking approximately 8 seconds to complete. Are there any t ...

streaming audio data from a MongoDB database to an HTML audio element

As part of my current project, I am delving into the realm of creating an audio player. The concept of database storage for files is relatively new to me, as my previous experience has mainly involved storing strings. Up to this point, here's what I ...

Guide for eliminating a specific row from a list in AngularJS

Despite my thorough search, I couldn't find a solution to my problem of deleting the CORRECT row from the list. Let's say I have the following array: $scope.rows = [{ "ID": 12, "customer": "abc", "image": "abc.jpg", },{ ...

Refreshing browser data with JQuery ajax when the browser is refreshed

Is there a way in JavaScript or jQuery to stop the page from refreshing (F5) and only update certain parts of the page using Ajax? I attempted the following code, but it did not work: $(window).bind('beforeunload', function(event) { ...

Add new content to an existing JSON file in a Node.js environment

I'm encountering an issue while attempting to insert new text into an existing JSON file. I've experimented with writeFileSync and appendFileSync methods, however the added text does not maintain JSON formatting even when utilizing JSON.stringify ...

React Leaflet causing a frequent map refresh due to context value updates

When I use map.on('moveend') to update the list of markers displayed in another component, I encounter a refreshing issue. The context in my project contains two arrays - one filtered array and one array with the markers. When I try to update the ...

Are there specific mathematical algorithms that lend themselves well to creating responsive HTML designs?

Tired of constantly guessing the percentage values to use with a specific number of divs and other elements in my design. I am looking to understand the mathematical calculations that determine the scaling required for different elements in order to main ...

Utilizing a JavaScript-sent URL within a PHP data grid: A step-by-step guide

I am working on a JavaScript function that fetches the URL of an API needed for a data grid. This API displays the students assigned to a particular teacher. The data grid must dynamically change based on the user (the teacher initiating the session), and ...

Is it possible to dynamically load JavaScript?

I'm currently working on a project that requires me to dynamically add JavaScript. I have a global.js file that contains all the global variables I need to add dynamically. However, I'm facing an issue where global.js is not being added before ut ...

Issue encountered in transferring Json data from controller to view, Laravel version 5.6

I'm struggling to convert the Json value received from my controller into a properly readable JavaScript value. This is my controller: $room = Room:: select('id', 'name', 'capacity', 'status') ...

"The magic of ReactJS's virtual DOM lies in its ability to keep a lightweight representation

Stumbled upon this statement in some form while browsing the web Whenever the data underlying a React application changes, a new Virtual DOM representation of the user interface is generated. This is where things start to get interesting. Updating the b ...

Tips on deobfuscating Next.js HTML from online sources

I am faced with the task of reconstructing a website that I scraped from the internet using wget. It seems to be built on next js, based on the presence of the _next folder. Even though I have no experience with nextjs and do not understand its inner worki ...

How to show dates in AngularJS using local formatting

One situation I'm dealing with involves setting a date for an event. The challenge is that the date picker needs to display the date in a localized format based on the country or region. I've been exploring various solutions in AngularJS, but so ...

The issue of the Angular 4 double click event not functioning properly on mobile devices

I have implemented a double click functionality in my code, which is working perfectly in desktop view. However, I am facing an issue when switching to mobile or tablet view as the double tap feature does not work. Below is a snippet of my code: HTML: & ...

Can JavaScript be used to dynamically assign events to elements on a webpage?

I am currently using the following code: if ( $.support.touch == true ) { $(window).on('orientationchange', function(event){ if ( full == false ) { self.hideAllPanels("7"); } }); } else { $(window).on(&apo ...

Is using .htaccess a reliable method for securing a specific file on the server?

Running a classifieds website comes with its own set of challenges, one being the need for an administrator to have the ability to remove classifieds at their discretion. To address this issue, I have developed a simple function that allows me to specify t ...

What's the reason behind beforeunload not triggering?

I've gone through numerous similar posts, but I'm struggling to figure out what's not quite right with this code snippet: $(window).on("beforeunload", function () { debugger handleBeforeUnload(); return false; }); function handl ...

Restricting the input range with JQuery

Need assistance with limiting user input in a text box for amounts exceeding a specified limit. Attempted using Ajax without success, considering jQuery as an alternative solution. Any expertise on this matter? function maxIssue(max, input, iid) { v ...