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

Unable to locate the variable named StyleSheet

I've been delving into React Native using this informative site https://www.tutorialspoint.com/react_native/react_native_animations.htm However, I encountered a setback when attempting to launch the app on my iPhone. An error message indicates that a ...

Undefined is returned after resolving - React - JavaScript API

Learning React and JavaScript is a bit challenging for me, especially when it comes to understanding how Promises and resolving work. I'm currently working on an API to log into an application with an internal SQL database. The queries are functionin ...

Stripping the prefix from a string using the .split function leads to an error message stating "Unexpected

When dealing with a string containing a unique prefix, I attempted to separate it into an array after the backslash character "\" by using the split function. Here is the string: i:0#.w|itun\allepage_fg This was my approach: function claimOrder ...

What is the best way to define file paths in a webpage to ensure that the same file works seamlessly on both server and

Currently, I am working on developing a website locally with the intention of later transferring it via FTP to my server. In my index.php file, there is a line that reads: <?php include($_SERVER['DOCUMENT_ROOT'] . "/includes/header.php");?&g ...

Setting up multiple base tags in AngularJS for different modules

When working with angularjs, there is a "#" that needs to be removed. This can be achieved by setting: $locationProvider.html5Mode(true); Additionally, adding the base tag ensures normal functionality when the page refreshes. If <base href="http://exa ...

Tap on the HTML5 video to exit the fullscreen mode

Objective I have successfully implemented a fullscreen video setup that triggers when a link is tapped on a mobile device. To maintain a clean aesthetic, I have hidden the HTML5 video controls using CSS. The desired functionality includes closing the full ...

Uncovering the Mystery: Extracting a Video Thumbnail from Brightcove Videos

Is there a way to extract the video thumbnail from Brightcove Video? <x:out select="$item/description" escapeXml="false" /> At the moment, the thumbnail is being retrieved within the description. ...

Is it possible to generate a PNG blob using binary data stored in a typed array?

I have a piece of binary data that is formatted as a PNG image. I am looking to convert it into a blob, generate a URL for the blob, and then showcase it as an image in various places where an image URL can be used, such as CSS. My initial approach invol ...

What is the best way to make a JSONP request using jQuery?

Whenever I try to access this API through the browser, everything works fine and I receive the correct response. However, when I attempt to call the API using jQuery AJAX, I encounter an error. *The script is being refused execution from 'http://api ...

Struggling to Implement Middleware on Router in ExpressJS?

In my application, I have both public and authenticated routes. The isAuthenticated function is used, for example, in a news controller. globalRouter: function (app) { app.use((req, res, next) => { logger.log("Endpoint: ", req.originalUrl); n ...

Translate CSS into JavaScript while maintaining selector understanding

I am interested in developing a tool that can read a .css file and generate a function that will accept an array of class names as input and output the corresponding styles for an element with those classes, represented as a JavaScript object. This tool wo ...

provide a hyperlink to the icon located in front of the navigation bar

I'm struggling to come up with a suitable title for this issue. What I am trying to achieve is placing a small icon in front of the navbar so that visitors can click on it and be directed to another site. Initially, I attempted to place the icon using ...

Tips for incorporating ajax to load a new webpage into a specific div container

I have a website with two pages. I want to load Page 2 into a div on Page 1 and then display Page 2 when clicked on. I'm attempting to implement the following code, but it doesn't seem to be working for me. As a beginner, I apologize if this is a ...

Retrieving JSON information using JavaScript

I am encountering an issue with the "Ion.RangeSlider" library. I am attempting to dynamically load values via JSON, but I am unable to get the slider to accept the data from the "from" field. It is important that the value is not hardcoded since the user h ...

Troubleshooting: The Google Analytics Universal Event Tracking Code is not functioning as

I am having trouble tracking clicks on an image that links to another site in a HTML widget on my website’s sidebar. I have implemented Google Analytics code, but for some reason, the clicks are not showing up in the "Events" tab of my analytics dashboar ...

dynamic jquery checkbox limit

I am working with the following HTML code: <input type="checkbox" id="perlengkapans" data-stok="[1]" onchange="ambil($(this))"> name item 1 <input type="checkbox" id="perlengkapans" data-stok="[4]" onchange="ambil($(this))"> name item 2 &l ...

When does the ng-disable function become activated?

Here's an example: <button ng-disabled="!isSomethingValid() || loading || disabled" ... class="btn btn-primary"> What determines the condition for the ng-disable attribute to evaluate its expression? ...

What is the best way to execute multiple Protractor test suites simultaneously?

Exploring Protractor for the first time. My goal is to run multiple test suites in a sequence. I have a complex angular form with various scenarios, each with its expected results. I want to execute all tests with just one command. Initially, I tried enter ...

What is the best way to set the page title on a server-rendered component when using the Next.js app router?

When loading a blog post from the server, I have access to details like the title of the post. However, based on the app router migration guide, this information is located outside my page. How can I update it? For more information, refer to the documenta ...

Attempting to transmit checkbox data in jade

I am currently developing an app with Express, Node.js, and Mongo. I have encountered an issue while passing checkbox values to my database. My goal is to only pass the values of checked checkboxes back to the database. In my index.jade file, I attempted ...