Constructing a binding object does not result in the creation of a valid object

I attempted to bind a constructor object:

"use strict";
    
let Person = function(name){
  this.name = name;
}

let age = {
  age: 128
}

let AgedPerson = Person.bind(age)
console.log(new AgedPerson("John"))

Expecting bind to set up a context with this pointing to an object and new to initialize and return it, I anticipated the output to be:

{
  age: 128,
  name: "John"
}

However, the output was:

{
  name: "John"
}

Why does the age field disappear after creating the object?

Answer №1

By utilizing the new keyword before a function, it ensures that the function is invoked with a fresh empty object assigned to the this value, even if .bind() was previously applied (essentially disregarding any prior this setting).

In cases where your function does not have a return statement and the new keyword is used, the default behavior is for the function to return the updated this value after execution. In this scenario of calling AgedPerson, the this context is initialized as an empty object {} due to the presence of new. As the function progresses, the name property is added to this object and ultimately returned implicitly, resulting in {name: "John"}.

The use of .bind() becomes relevant when the function is called through other methods like (), or with .call() and .apply(), but not applicable when employing new. For example:

"use strict";

const person = function(name) {
  this.name = name;
}

const age = { age: 128 };

const agedPerson = person.bind(age)
agedPerson("John"); // modifies the age object by reference
console.log(age); // { age: 128, name: "John" }

Answer №2

Keep in mind that when following Nick Parsons' advice, simply invoking a constructor on an object does not transform the object into a genuine instance of Person. To rectify this, you should establish its prototype.

In addition, utilizing Function::call() allows you to meld the binding and invocation processes into a single step.

"use strict";

const Person = function(name) {
  this.name = name;
}

const age = { age: 128 };

Person.call(age, 'John');
Object.setPrototypeOf(age, Person.prototype);

console.log('age is Person:', age instanceof Person);
console.log(age); // { age: 128, name: "John" }

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 proper way to retrieve a function from an angular module?

Here is a snippet of AngularJS code for a wallet module: angular.module("app.wallet", ["app.wallet.directive", "app.wallet.service"]), angular.module("app.wallet.service", []).factory("$wallet", ["$rootScope", "$$http", "$e", "$toast", "errorMap", "$popu ...

Choosing a specific option from a list of multiple choices with javascript

I have a selection with multiple options. Currently, the selected values are '2,4,5'. <select id="testID" multiple="multiple"> <option value="1">test Value1</option> <option value="2">test Value2</option> ...

Pass a data variable to an HTML file using express's sendfile function (quick inquiry)

Currently utilizing Node.JS, path, and express for running an HTML webpage. I need to pass a variable to the HTML file for its utilization: var client_cred_access_token = 'fakeToken'; ... app.get('/', function (req, res) { res.se ...

What is the best method to retrieve the current time in minutes using the Timer component?

I have integrated the react-timer-hook library into my Next.js application to display a timer. The timer is functioning correctly, but I am encountering an issue where I cannot retrieve the current elapsed time in minutes during the handle form event. My g ...

Error: JQuery's on() function is not defined

After modifying the code in the original and changed code boxes, I'm now encountering an Uncaught Type error: Undefined is not a function. Any thoughts on why this might be happening? Thanks Original: $('.comment').click(function(e){ ...

Navigating using TypeScript with React Navigation

When it comes to navigating in my app, I rely on useNavigation from '@react-navigation/native'; This is how I transfer data between two screens: type UserDetailsProps = { onDeleteContact: (id: number) => void; route: any; }; I'm try ...

The JavaScript functionality is not functioning properly within the webView that has been loaded from the

Attempting to display the offline version of Python documentation in a webview from the asset folder. The offline docs function correctly in my desktop web browser offline, but encounter issues in the webview (such as jquery is missing). @SuppressLint("Se ...

Having trouble executing an npm script - getting an error message that reads "Error: spawn node_modules/webpack/bin/webpack.js EACCES"

After installing and configuring Linux Mint, I encountered an error when trying to run my project with the npm run dev command. The error message "spawn node_modules / webpack / bin / webpack.js EACCES" keeps appearing. I have attempted various methods fo ...

Is there a way to prompt the native browser message for HTML5 form validation on a custom element?

https://i.sstatic.net/3wuWh.png Can the native validation UI be activated on non-default input elements like divs or similar? I want to develop a custom React element with validation without relying on hidden or invisible input fields. ...

Connecting to Travel Events in a Page

When I try to bind a router event in the initialize method, I encounter some unexpected behavior: var View = Backbone.View.extend({ initialize: function() { router.on("route:test", this.update); }, update: function() { con ...

Stop the inheritance of CSS and JavaScript in ASCX files

Currently, I have an application that consists of only one aspx page called Default.aspx. This page dynamically loads .ascx controls as required, all of which utilize the same JS and CSS file. I am now considering implementing Bootstrap on specific control ...

Guide on utilizing automatic intellisense in a standard TextArea within a web application

I have successfully created an Online compiler web application that is currently running smoothly. However, I am now looking to enhance my application by implementing intellisense in the TextArea where the program is being typed. For instance, if I type "S ...

What is the method to generate a list where every item is a list within AngularJS?

Is it possible to create a nested list in AngularJS 1.3 where each option contains its own list? I've tried implementing it using this, but the select tag seems to cut it short. Any solutions or workarounds for this issue? <body ng-app=""> &l ...

What are the best strategies for addressing security risks in Axios versions 1.0.0 to 1.5.1 and those greater than or equal to 1.3.2?

After running npm install, I encountered a moderate vulnerability. How can I resolve this issue? 1 moderate severity vulnerability To fix all problems, run: npm audit fix Run `npm audit` for more information. # npm audit report axios 1.0.0 - 1.5.1 S ...

Guide to filtering out cookies using express-winston

After reviewing the README for express-winston, it appears that removing the headers from the logged line is quite straightforward: we can easily do so by adjusting the requestWhitelist option. However, this will disable logging all headers. Is there a wa ...

Accessing Array of Objects Transferred via AJAX in JSP

Regarding the query discussed in this link, how can I extract the outcomes in JSP? The main issue is that my JavaScript contains the following: data = [ { id: "333", date: "22/12/2015" }, { id: "333", date: "22/12/2015" ...

Display the total combined hours of all events for each day in FullCalendar

Currently, I am utilizing the FullCalendar plugin created by Adam Shaw in conjunction with knockoutjs. With this setup, I have successfully implemented functionality to add, delete, and drag-and-drop events. However, in both week mode and day mode, I am ai ...

Launching a personalized Mailchimp form

I am trying to implement a custom mail chimp form that pops up upon page load, similar to what Groupon and Fab do. I have the code for the form copied on our server but I'm struggling to create a pop-up effect when the page loads. I have tested shadow ...

How can I save a value in JavaScript once the page has finished loading?

$("#divid1").click(function(){ $("#divid1").hide(); //this should remain hidden even after refreshing the page $("#hideid1").hide(); //this should remain hidden even after refreshing the page $("#id1").show(); //this should remain visible even ...

Affixing a navigation bar to the top while scrolling

Does anyone know how to create a navigation bar that will "dock" to the top of the browser when scrolled to, and undock when scrolled back up? Check out my code snippet here: http://jsfiddle.net/gLQtx/ $(function() { var initPos = $('#stickyNav&apo ...