What is the best way to retrieve the specific property from a bound function?

I'm looking to retrieve the value of a specific property from a function that has already been bound.

function foo(){
  console.log(this.a)
}
const bar = foo.bind({a:1})
bar() // Outputs 1
bar.getThis() // expected result is { a: 1 }

Given the code snippet above, what would be the proper way to extract the bound object { a: 1 } from the variable bar?

Answer №1

To achieve this, a method to extend the built-in `bind` functionality is by modifying it as shown in the code snippet below.

Function.prototype.__bind__ = Function.prototype.bind;

Function.prototype.bind = function(object) {
  var fn = this.__bind__(object);
  fn.getThis = function () {
   return object;
  }
  return fn;
}

function example(){
  return this.value
}
var output = example.bind({value:1})
console.log(output());
console.log(output.getThis())

Answer №2

Accessing [[BoundThis]] is restricted as it is considered an internal property of bound function objects.

However, you can still view it in the console:

https://i.stack.imgur.com/FHydr.png

The pre-bound this value of a function Object is created using the native built-in Function.prototype.bind method. Only ECMAScript objects created through Function.prototype.bind have a [[BoundThis]] internal property.

According to Bergi, "to utilize it within your program logic, you would need to implement your own version of bind that reveals this value as a property".

Although, if modifications can be made to the foo() function, you could try something like this:

function foo() {
  console.log(this.a);

  return {
    getThis: () => this
  };
}
const bar = foo.bind({ a: 1 });

console.log(bar().getThis()) // { "a": 1 }

Answer №3

In order to retrieve the enclosed object { a: 1 }, you can simply return or display this:

function example() {
  console.log(this);
}

const sample = example.bind({ a: 1 });

sample(); // { a: 1 }

I trust this explanation proves beneficial.

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

Filter error - Unable to retrieve property 'toLowerCase' from null value

When filtering the input against the cached query result, I convert both the user input value and database values to lowercase for comparison. result = this.cachedResults.filter(f => f.prj.toLowerCase().indexOf((this.sV).toLowerCase()) !== -1); This ...

Can you explain how differential inheritance works in JavaScript?

This response to a question about the Object.create() method in JavaScript on SO discusses the concept of differential inheritance. The explanation given is as follows: This particular technique enables you to easily establish differential inheritance, ...

jQuery function duplicates row in table

I am trying to utilize jQuery to generate a table, but I seem to be encountering an issue with my code: function showGrid(url, container, columns, page) { jQuery(container).empty(); var tr = jQuery("<tr class=\"mobileGridHeader\"> ...

What is the method for including a data attribute in the text of a cell using Datatables Editor?

When initializing datatables along with editor, I typically use the following code: columns: [ { data: "name", className: 'noEdit clickTextToOpenModal' }, In this line of code, I am able to set the className attribute. However, is i ...

Offspring of div should have equal height without the top and bottom padding

Looking to ensure that the height of child divs matches the height of the parent divs. Currently, the divs expand as the page is resized. This is for search results, so there are multiple identical code blocks. function matchHeight() { $result = $(&a ...

Vue's span function is yielding the promise object

In my Vue component, I am using the function getOrderCount to fetch the number of orders from a specific URL and display it in one of the table columns. <div v-html="getOrderCount(user.orders_url)"></div> async getOrderCount(link) { ...

Load information into array for jqGrid display

I am attempting to populate my JQgrid with data every time I click the "1" button, but I am encountering difficulties. As a newbie in jQuery, I am able to display the data in a p tag without any issues. Currently, I am considering whether to use push or a ...

Custom label slots in q-file for the Quasar file picker for personalized file selection label

Can you provide guidance on how to properly display custom label slots in Quasar? I am looking to incorporate icons or images using the label slot. Below is my data(): data() { return { showLabel: true, labelText: "My custom Label& ...

The jQuery window.on event is not functioning when trying to handle the same hash change

How to fix jQuery window.on hashchange issue when clicking on the same hash? See the code snippet below for a potential solution: function addMargin() { let header = $('.header__wrapper').outerHeight(); let headerHeight = $('body& ...

The AngularJS $rootscope $destroy event is not being triggered, resulting in timeouts not being cancelled

Below is the code snippet that I am currently working with: function initialize() { var defer = $q.defer(); var deferTimer = $q.defer(); var cancelTimeout = $timeout(function() { if (defer !== null) { ctrlr.setProcessingParameters('X ...

The submission of an Angular form results in errors such as being unavailable or

After building a registration page component in Angular and following tutorials, I encountered a frustrating bug. When pressing the submit button on the form, the console would display "undefined" when attempting to access the NgForm's value. However, ...

What is the process for reporting a security vulnerability in an npm package if you are the maintainer and publisher?

If I discover a security flaw in my published packages, how can I indicate which versions are vulnerable so that users running `npm audit` will be alerted? ...

Adjust Mui Autocomplete value selection in real-time

I have implemented Mui AutoComplete as a select option in my Formik Form. <Autocomplete disablePortal options={vendors} getOptionLabel={(option) => option.vendor_company} onChange={(e, value) => {setFieldValue("vendor_id", value. ...

An operator in rxjs that transforms an Observable of lists containing type X into an Observable of type X

Currently, I am facing a challenge while dealing with an API that is not very user-friendly using Angular HTTP and rxjs. My goal is to retrieve an Observable<List<Object>> from my service. Here's a snippet of the JSON output obtained from ...

Utilize Javascript to conceal images

On a regular basis, I utilize these flashcards. Recently, I have started using images as answers. However, I am facing an issue - I am unable to conceal the pictures. My preference is for the images to be hidden when the webpage loads. function myShowTe ...

Conceal the input field prior to making a selection from the dropdown menu

I have implemented a drop-down menu for selecting dependencies, similar to how it functions in JSFiddle. $('#user_time_zone').on('change', function() { dateCalender = $(this).val(); if (dateCalender == 'Single Date') { ...

Unusual marker appearing on every page utilizing ionic v1 and angularjs

For some unknown reason, a dot appears at the upper left side of each page in my webapp: https://i.stack.imgur.com/nN61t.png It seems to be an issue with the HTML code. When I run the snippet below, the dot is visible: <ion-view view-title="Send fe ...

How to use mousedown event in Three.js to create line drawings

I've tried multiple approaches to achieve this effect. I'm looking to draw a line on mouse down event, and despite researching various resources, I haven't been able to come up with a solution. Currently, I'm utilizing the RayCaster met ...

Sending an array object from Ajax to Django Framework

AJAX Script Explanation: Let's consider the variable arry1D contains values [0,1,2,3,4] $.ajax({ url: "{% url 'form_post' %}", type: "POST", data: { arry1D: arry1D, 'csrfmiddlewaretoken': tk }, ...

When trying to set up Plaiceholder in a Next.js/Webpack 5 environment, you may encounter the following issue: "Error: Module not found - Can't resolve 'child_process

While working on my Next.js application, I encountered an issue after installing/importing Plaiceholder for generating placeholder images. The error message I received is: Module not found: Can't resolve 'child_process' Node version: 14.18. ...