Constructor not executing when using Object.create

Attempting to instantiate a class within a static method, I am using Object.create(this.prototype), which appears to be functioning correctly. Nonetheless, when I check the console, my property items is showing as undefined.

The base class called model looks like this:

export default class model {

  protected items: any = {}

  public constructor(options: ModelSettings) {
    // Implement some logic here
    // items property not being set before compilation
  }

  public static create(options) {
    let t = Object.create(this.prototype) as any
    console.log(t.items)
  }
}

Next, there is a class named purchases that extends the model:

export default class purchases extends model {
  public constructor() {
    super({table: 'purchases'})
  }
}

To invoke it, use the following code snippet:

purchases.create({ my: 'options' })

The create method instantiates an object of purchases and operates smoothly. However, the property items remains undefined, as mentioned previously.

Could it be that Object.create() does not execute the constructor?

Answer №1

It does not invoke the constructor. Instead, it simply generates an object without a strong type {} like this

const obj = {}

and assigns the prototype of that object to the specified prototype.

You can easily utilize new this() in place of Object.create()

Check out the Demo

Answer №2

The constructor is not automatically called; instead, it simply sets the prototype. You must manually call the constructor yourself.

// Set prototype
let instance = Object.create(this.prototype) as any;
// Call the constructor, make sure 'this' points to the constructor 
this.apply(this);

One way to ensure both the prototype chain and constructor are used is by doing the following:

instance = new this();

Answer №3

When building something, it is recommended to utilize the new keyword:

const item = new this;

If you insist on creating it manually, the process becomes a bit more intricate:

const item = Object.create(this.prototype);
this.call(item);

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

The jQuery draggable feature ceases to function after it has been dropped

I have a scenario with two divs, each housing a list of quantities and items. These items are draggable, and the div containing them is droppable. The condition here is if an item with the same name exists in the div, it cannot be dropped on that div again ...

Is there a way to trigger a confirmation function for form submission exclusively when clicking one specific submit button, and not the other?

Here is the layout of my form: <form action="newsletter.php" name="newsletter" id="newsletter" method="post"> <input type="submit" value="Submit" class="c-btn" id="submit_value" name="submit_value"> <input type="submit" value="Send" cla ...

Electron / Atom Shell unable to locate specified module

I am completely new to npm, node, and Electron. Here is the structure of my folder: -package.json -index.html -main.js -js/myStuff.js -node_modules In the file myStuff.js, I have a line that says var chokidar = require('chokidar'); but it keep ...

Display input field in AngularJS when radio button is selected

My JavaScript array looks like this: $scope.quantityMachines = [ { 'snippet' : 'One' }, { 'snippet' : 'Two' }, { 'snippet' : 'Three or more', 'extraField' : true }, { ' ...

Import reactjs modules without the need for Browserify, Webpack, or Babel

I am attempting to set up a TypeScript HTML application in Visual Studio. My goal is to incorporate reactjs v0.14.7 without relying on tools like Browserify. But, how can I utilize the react-dom module in this scenario? Let's set aside TypeScript fo ...

Incorporating local JSON data into HTML: A Step-by-Step

I'm completely new to javascript and the utilization of json. What I want to accomplish is quite straightforward, although I am encountering difficulties. My objective is to create a website consisting of two pages: one that showcases artists and ano ...

What is the best way to enable editing of a form when the edit button is clicked?

I have created a simple profile page where users can edit their profile information. I have placed a button at the end of the page. Initially, the form should be uneditable, but when the button is clicked, the form becomes editable. I attempted to use `dis ...

The issue with Angular-gettext is that it fails to update dynamically generated strings in the code

Whenever I try to set the language using the code gettextCatalog.setCurrentLanguage(langString);, it doesn't seem to affect my side-nav menu. My side menu has two possible states: expanded or collapsed, and I use ng-include to control its content base ...

Authentication using tokens - JSON Web Tokens

While working with jsonwebtoken in Node, we generate a unique token for each user and return it to them. But when the user sends this token in the authentication header (Authentication: <token>), how does jwt differentiate between tokens from diffe ...

How can I prevent the browser's back button from functioning on an AngularJS webpage?

Is there a way to disable the browser's back button and refresh button in Angular? For example, in my source code: Page Source: "use strict"; .controller("wizardSecondController", function($scope, $state, $stateParams, wizardManager) { $scope.$on ...

Serve as a proxy for several hosts with identical URL structures

I've been utilizing the http-proxy-middleware to handle my API calls. Is there a way to proxy multiple target hosts? I've searched for solutions in the issues but still haven't found a clear answer. https://github.com/chimurai/http-proxy-m ...

Creating an HTML file using PUG in a local environment (using npm and gulp)

Is there a way to automatically generate an HTML file with the same name as my Pug file whenever I save using gulp? I've checked all the documentation on but it only explains how to return Pug content in console... ...

Ways to showcase every resource from an API in React JS

I need help with adding code to display products along with their images from an API in my existing code. Can someone assist me with this? import React, {useState, useEffect} from 'react' import "bootstrap/dist/css/bootstrap.min.css" im ...

Tips on maintaining a constant number of elements displayed within a container while scrolling using *ngFor

In an effort to improve the performance of loading a large amount of data inside a container div, I implemented a solution. It initially worked fine, but as I continued to append elements to the list while scrolling down, it started to slow down significan ...

Is it possible to trigger a Bootstrap 5.2 Popover within an "if" statement?

As part of my input validation process, I am utilizing popovers. However, I am struggling with the syntax to make it work as intended. https://jsbin.com/sufitelodo/1/edit?html,js,output The JSBin provided serves as the foundation for this issue. I am un ...

Retrieve items from a JSON file based on the user input ID in a React project

Hi there, I'm looking for guidance on how to extract items by name from a JSON file based on user input. The JSON file contains both an id and name for each item. My goal is for the user to enter a number, which will then display the corresponding ite ...

"Array.Find function encounters issues when unable to locate a specific string within the Array

Currently, I am utilizing an array.find function to search for the BreakdownPalletID when the itemScan value matches a SKU in the array. However, if there is no match found, my application throws a 'Cannot read property breakdownPalletID of undefined& ...

How can we create lists using parentheses specifically with Javascript or jQuery?

I am looking to create a formatted list using <ol> and <ul> tags with parentheses included. (1) List1 (2) List2 (3) List3 (4) List4 The challenge is to achieve this formatting purely with javascript or jQuery, without relying on any external ...

Displaying a progress bar during image uploads in PHP without using AJAX

I am in the process of uploading a file on my website and it is working well. However, I would like to display a progress bar while the upload is taking place. I have considered using ajax for this purpose, but I am unable to use ajax. Is there a way to ac ...

Creating custom generic functions such as IsAny and IsUnknown that are based on a table of type assignability to determine

I attempted to craft a generic called IsAny based on this resource. The IsAny generic appears to be functioning correctly. However, when I implement it within another generic (IsUnknown), it fails: const testIsUnknown2: IsUnknown<any> = true; // iss ...