Accessing the runtime 'this' value from an external function in JavaScript

this within a function is dynamically set at runtime:

var person = {  
  hello: function(thing) {
    console.log(this, " says hello " + thing);
  }
}

// the code:
person.hello("world");

// is similar to:
person.hello.call(person, "world");  

Is there a way, after binding a function to an object, to retrieve that object from a reference to the bound function? For example:

var mysteryFunction = person.hello;
mysteryFunction.getMyRuntimeThis() // returns: person

Answer №1

Python and JavaScript have different ways of handling objects, so directly transferring methods is not feasible. One workaround is to create a new object with all methods bound to it:

var bindMethodsToObject = function(obj) {
  var newObj = {};
  Object.keys(obj).forEach(function(key) {
    var value = obj[key];
    if(value.bind)
      value = value.bind(obj);
    newObj[key] = value;
  });
  return newObj;
}

//

var person = {  
  name: 'Joe',
  greet: function(thing) {
    console.log(this.name + " says hello " + thing);
  }
}

var sayHello = bindMethodsToObject(person).greet;
sayHello('there')

A more efficient way to achieve this is by using proxies.

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

Finding the value of a radio button dynamically created by jQuery

I am having an issue retrieving the value of a radio button that is generated using jQuery. I suspect there may be some problems with event handling. Below is my code: HTML <div id="divOption1"></div> The jQuery script to generate t ...

"Maintaining Consistency: Ensuring The First Row is Repeated on Every

When trying to save a PDF using jspdf, I encountered an issue with tables in my HTML. The tables do not have headers, but JsPDF is automatically repeating the first row of the table on every page, causing overlap. I don't want headers on every new pag ...

Steps for linking a page to a modal without embedding the page's content within the modal

Here is a snippet of code for a modal (from Twitter Bootstrap) that I am currently working with: <!-- Large Modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">Large Modal</button&g ...

What are the advantages of using HttpClient compared to fetch?

With the introduction of Angular 2+, HttpClient now facilitates HTTP requests sent down an RxJS observable. I'm curious about why one would opt for using HttpClient's API instead of the standard fetch for individual HTTP requests. I have a good ...

Leverage the power of mathematical functions within Angular to convert numbers into integers

In my Angular 7 Typescript class, I have the following setup: export class Paging { itemCount: number; pageCount: number; pageNumber: number; pageSize: number; constructor(pageNumber: number, pageSize: number, itemCount: number) { thi ...

The issue of `Console.log` displaying as undefined arises after subscribing to a provider in Ionic3

In the process of implementing the Spotify api into my Ionic 3 app, I encountered an issue where the data retrieved appears as undefined when attempting to log it. Let me share some code and delve deeper into the problem. Here is the function getData() tha ...

Adjustable Panel Width

Is there a way to have the width of the bottom panel expand to col-md-12 when the top panel is collapsed, and then return back to col-md-8 when the user expands the top panel again? I'm still learning, but here's what I have managed to code so f ...

The Console.log() function displays the current state and value of a promise object within the Q library

Whenever I attempt to print a promise object from Q, the result that I receive is as follows: var Q = require('q'); var defaultPromise = new Q(); console.log('defaultPromise', defaultPromise); defaultPromise { state: 'fulfilled& ...

What steps should I take to resolve the textarea border bottom CSS effect?

My simple border bottom animation is working fine with a basic input element, but it's not functioning properly when used with a textarea. (If using JavaScript is necessary for a solution, please provide guidance) How can I adjust the height of a te ...

Updating line connections between objects in Three.js while rendering

I am working with a three.js canvas that contains circles moving independently. Initially, these circles are connected by a single line that follows the same geometry as their positions. However, I am facing difficulty updating the line's geometry wh ...

ReactJS does not display an image from the local file system

I'm currently facing an issue while trying to load an image in my next.js project. I am using the native tag from react, but the image is not appearing on the page. I have provided the links to my two JavaScript files (styles and component) below. An ...

Error message: "Index is not defined when using ng-repeat in AngularJS

I have a challenge toggling the button on and off within an ng-repeat. The 'View on Map' function works fine, but when I switch to 'Remove Marker', it throws an error 'ReferenceError: passedIndex is not defined' in the console ...

Tips for correctly loading all elements on an HTML page before making CSS modifications

This question has been asked several times in the past. I am asking because when I used the on ready callback in jQuery, it did not change the placeholder text of my element "search_input". $( document ).ready(function() { $("#search_input").attr(' ...

How come submitting a form without refreshing does not update the database with new values?

I'm encountering an issue with my form and script that is supposed to connect to the operation.php class. Despite having everything set up correctly, the data is not being added to the database and the page does not refresh. I'm perplexed as to ...

Ways to determine the position of elements when they are centered using `margin:auto`

Is there a more efficient way to determine the position of an element that is centered using CSS margin:auto? Take a look at this fiddle: https://jsfiddle.net/vaxobasilidze/jhyfgusn/1/ If you click on the element with the red border, it should alert you ...

Is it possible to utilize the map method to extract objects that are nested multiple layers deep?

I am working on accessing the change order information in order to compile a list of all the change_order_names. The code I am currently using is yielding the results displayed below. Could someone assist me in understanding how to access the change order ...

What is the best way to eliminate the border of an expansion panel in Material-UI?

Is there a way to eliminate the border surrounding the expansion panel in Material-UI? ...

Looking for assistance with deleting a child element in an XML file using PHP

I need help figuring out how to delete a child from my jobs.xml file with a PHP script. My jobs.xml file looks like this: <jobs> <event jobid="1"> <title>jobtitle</title> <desc>description</desc> &l ...

arrangement of columns within the <select> element

I have been attempting to create a column layout inside of <select> using CSS, but so far I have been unsuccessful. https://i.sstatic.net/ltIDl.png This is the HTML code I have tried: <select id="select-bill-period"> <option>Select ...

Error: Unexpected termination of data in JSON file on line 2, starting at the first character

I keep encountering an error while trying to execute a basic JSON request. Check out the following PHP code that contains the data: <?php header('Content-Type: application/json; charset=utf-8'); $wealth = array( "name" => &q ...