Maintain the functionality of an object even when it is created using the "bind" method

I'm working with a function that has the following structure:


var tempFun = function() {
    return 'something';
}
tempFun.priority = 100;

My goal is to store this function in an array and bind another object to it simultaneously, like so:


var funArray = [];
var newObj = {};

funArray.push( tempFun.bind(newObj) );

After this process, I want to access the function's property as follows:


funArray[0].priority

However, when I try to do this, it returns undefined. Is there a way to retain the property of the function while binding a new object to it?

Answer №1

No, however it is possible to create a custom function for this purpose;

Function.prototype.bindAndCopy = function () {
    var ret = this.bind.apply(this, arguments);

    for (var x in this) {
        if (this.hasOwnProperty(x)) {
            ret[x] = this[x];
        }
    }

    return ret;
}; 

... which can be utilized as follows;

var funArray = [];
var newObj = {};

funArray.push( tempFun.bindAndCopy(newObj) ); 

Answer №2

When you use the bind method in JavaScript, it returns a new function that encapsulates the original one. In order to make sure all properties are maintained, you must manually copy them to the new function:

var boundFunction = originalFunction.bind(newObject);
boundFunction.priority = originalFunction.priority;

arrayOfFunctions.push(boundFunction);

To synchronize the properties between the two functions, you can define a getter and setter for each property like so:

Object.defineProperty(boundFunction, 'priority', {
  get: function() { return originalFunction.priority; },
  set: function(val) { originalFunction.priority = val; }
});

Answer №3

Quoting MDN:

When the bind() method is used, it creates a brand new function that will have its this keyword set to the specified value. Additionally, any arguments provided will come before the ones passed when calling the new function.

Due to this behavior, using .bind() may not be the most effective approach for your current goal. Instead of resorting to jQuery mappers or restructuring your code to utilize .prototype, one potential solution could involve the following:

var obj = {};
for (var i in tempFun) {
    if (tempFun.hasOwnProperty(i)) obj[i] = tempFun[i];
}

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

How can I utilize the LED flash on a Windows Phone using WinJS?

Currently delving into the world of WinJS and endeavoring to create an application that involves operating the LED Flash. I am seeking guidance on how to properly access the LED Flash functionality to allow for toggling it ON or OFF. Your insights on how ...

Tips for embedding the <img> element inside the <a> element

I'm attempting to place an image within a hyperlink tag. Current code: <div class="Sample"> <a href="http://www.Sample.com"> <img src="http://www.Sample.com/Sloth.jpg"> </a> </div> I wish to add <img class= ...

Responsive Bar Chart using jQuery Mobile and ChartJS that appears on the screen only after resizing

I have been experimenting with adding a responsive bar chart using Chart.js in one of my JQM projects. Here is what I have accomplished so far: http://jsfiddle.net/mauriciorcruz/1pajh3zb/3/ The Chart needs to be displayed on Page Two and it should be res ...

Implementing jQuery getScript in a Ruby on Rails 3 application

After watching a railscast tutorial on loading records through ajax when a link is clicked, I implemented the following javascript: $(function() { $("#dash_container th a").live("click", function() { $.getScript(this.href); return false; }); } ...

Struggling to get the Ant design button to launch an external link in a new tab using React and NextJS

I have an Ant button set up like this: <Button style={{ borderRadius: '0.5rem' }} type="default" target="_blank" ...

The gradual disappearance and reappearance of a table row

I am struggling with making a row fade out when a specific select value is chosen (such as "termination"), and fade in when any other option is selected. The code works perfectly fine when the div ID is placed outside the table, but once I encapsulate it w ...

Ways to activate an event based on the dimensions (width/height) of

Exploring ways to implement an if statement based on specific width/height values using this code example. Check out the code snippet here My approach: <p id="confirmation">Try again!</p> <script> if (new dynamicSize.width() < ...

A useful Javascript function to wrap a string in <mark> tags within an HTML document

I have a paragraph that I can edit. I need to highlight certain words in this paragraph based on the JSON response I get from another page. Here's an example of the response: HTML: <p id="area" contenteditable> </p> <button class="bt ...

Do not use unnecessary variables for storing references in ES6

Despite using react es6, I am still unsure how to refrain from needing to use the variable that for this scenario: const that = this; UploadApi.exec(file).then(data => { that.setState({ loading : false}); }); ...

NextJS build problem causing all content to become static

As a newcomer to NextJS with prior experience in basic React apps, I recently attempted to deploy a CRUD NextJS app (utilizing prisma and mongoDB). Everything runs smoothly with npm run dev, but issues arise when transitioning to npm run build followed by ...

What is the best way to save characters from different languages into variables?

I created an application that reads words from a TXT file and stores them in a database. The issue arises when I encounter words from other languages that contain non-English characters, resulting in the following problem: Is it possible to store these ch ...

The Express application appears to be unresponsive, but the data has been successfully saved to the MongoDB database. An error with the

Currently, I am delving deeper into the MERN stack and working on a straightforward CRUD application utilizing it. One of the recent additions to the app includes validators implemented through express-validator for handling requests. However, an issue ari ...

Having trouble with React Testing Library throwing an error every time I try to use fireEvent on an input text?

When attempting to utilize the "fireEvent" method from React Testing Library, I encountered an error as shown below: MainSection.test.js: test('Verifying SearchBar functionality', async () => { render(<SearchBar />); const text ...

Using Next-Image Relative Paths can lead to 404 errors when being indexed by web crawlers

I have implemented next-image in my project, and all the images are hosted on Cloudinary. The images display correctly, but when I run a website analysis using tools like Screaming Frog, I receive numerous 404 errors. This is because the tools are looking ...

The VueJS Chosen directive fails to refresh when new options are selected

Struggling to populate my jQuery Chosen dropdown field with AJAX data using VueJS. Unfortunately, when trying to update the values, the Chosen dropdown does not reflect the changes. I've experimented with different approaches, including manually trig ...

What is the best way to retrieve variable data from a Node.js function in an external context?

This Node.js function is designed to retrieve data from Analytics: function getDataFromGA(Dimension, Metric, StartDate, EndDate, MaxResults) { var fs = require('fs'), crypto = require('crypto'), request = require('request& ...

"Challenges encountered when using map function to dynamically fill select dropdowns in React with Material UI

I am currently working on populating Material's UI with a list of countries using the following code: import React from "react"; import FormControl from "@material-ui/core/FormControl"; import InputLabel from "@material-ui/core/InputLabel"; import Se ...

Various successful functions in Ajax

I am currently using an Ajax script to fetch data from my database and insert it into multiple textboxes. Along with posting the data, I also need to perform calculations using these textboxes. However, upon running the script, I noticed that all calculat ...

Issue with Jquery's .html() function not functioning properly when trying to select HTML

I am currently working on a piece of code that looks like this: $price = $(element) > $('.main_paket_price').attr('name'); alert($price); Basically, I am trying to select an element inside element which has the class main_paket_pri ...

Chat application using Node.js without the need for Socket.IO

Recently delving into the world of Node.js, I stumbled upon the fs.watchFile() method. It got me thinking - could a chat website be effectively constructed using this method (along with fs.writeFile()) in comparison to Socket.IO? While Socket.IO is reliabl ...