Retrieve the parent object within a constructor function

Is there a way to access the parent object when calling a function contained inside that object as a constructor without explicitly referring to it? Take a look at this scenario:

var customers = {
    // Number of customers
    count: 0,

    // Naturally _this is undefined
    _this: this,

    // Constructor function
    CreateCustomer: function (name, email) {
        this.name = name;
        this.email = email;

        // How can I access the containing object without explicitly referencing it?
        customers.count++;
    },

    getCount: function () {
        return this.count;
    },
};

If I attempt to call the CreateCustomer function as a constructor, then this will point to the empty object created by the new operator. For example:

var customer = new customers.CreateCustomer('Alice', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="14667d777f54716c75796478713a777b79">[email protected]</a>')

In such cases, how can I access the parent object customers without directly mentioning it?

Answer №1

It appears that you are searching for a static property, which is still in development for JavaScript.
This feature is currently experimental.

Currently:

Static (class-side) data properties and prototype data properties must be defined outside of the ClassBody declaration:

Rectangle.staticWidth = 20;
Rectangle.prototype.prototypeWidth = 25;

Since what you are trying to achieve resembles Joshua Bloch's concept of a static factory method or factory method pattern in general, it might be beneficial to move the new keyword up to the CreateUser method of the users object.
By doing this, you can utilize closure to store the reference to the users object, implement a nested constructor function, and invoke it with the new keyword.

Here is a working example:

var users = {
    count: 0,

    CreateUser: function (name, email) {
        var self = this;
        const createUser = function(name, email) {
              this.name = name;
              this.email = email;
              self.count++;
  
        }
        return new createUser(name, email)
    },

    getCount: function () {
        return this.count;
    },
};
var user = users.CreateUser('Rick', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c2b0aba1a982a7baa3afb2aea7eca1adaf">[email protected]</a>')
console.log(user)
console.log(users.getCount())
users.CreateUser('Morty', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="375a5845434e77524f565a475b521954585a">[email protected]</a>')
users.CreateUser('Jerry', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a1b0a0a161f093a1f021b170a161f54191517">[email protected]</a>')
console.log(users.getCount())

Answer №2

Make sure to pass it as a clear parameter.

let people = {
    total: 0,
    _this: this,

    // Function for creating new user
    CreatePerson: function (name, email, parent) {
        this.name = name;
        this.email = email;

        // Is there a better way to refer back to the main object?
        parent.total++;
    },

    getTotalCount: function () {
        return this.total;
    },
};

let person = new people.CreatePerson('Emily', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="791b101a122911080d101c152e131f1d">[email protected]</a>', people);

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

Numerous occurrences of Setinterval

I am currently facing a minor issue with my code. My setup involves an auto-playing rotating fadeIn fadeOut slider, where clicking on a li will navigate to that 'slide' and pause the slider for a specific duration. The problem arises when a use ...

Suggestions for rendering this JSON format

I am attempting to iterate through this JSON format, I have tried following this method but I am a bit confused with my code How to iterate JSON array in JavaScript?. Also, I have a question, is this actually a valid JSON format or something different bec ...

Tips for dynamically resizing a div element as a user scrolls, allowing it to expand and contract based on

I was working on a project and everything seemed easy until I hit a roadblock. What I am trying to achieve is expanding a div to 100% when scrolling down to the bottom of the div, then shrink it back to 90% at the bottom and do the reverse when scrolling ...

Is there a way I can incorporate v-for with a computed variable?

I am trying to display navigation items based on my authority and other conditions. Below is the code I am using: <template v-for="(subItem, index2) in item.children"> <v-list-item sub-group link :to="subItem.link" exact ...

Here's a helpful guide on verifying the presence of a value within an array in Quasar

const myproducts = ref([]) const items = ref([ { id: 1, item: 'Vaporub 50Gm' , barcode: '123456'}, { id: 2, item: 'Herbal Cool Oil (300+100)Ml', barcode: '123456' }, { id: 3, item: 'live Oil Bp 70M ...

Iterate through the list retrieved from the backend

I have a list coming from the backend that I need to iterate through and hide a button if any element in the list does not have a status of 6. feedback The response returned can vary in length, not always just one item like this example with 7 elements. ...

The Javascript query is returning an [object Object] data type

I am facing an issue with a JavaScript file that is querying a SharePoint list. Specifically, the Priority drop down in the query result is displaying as [object OBJECT]. I suspect it has something to do with the var query string where I have added the &ap ...

AngularJS: resolving route dependencies

I have a variable $scope.question that contains all the questions for the page. My goal is to loop through the questions page by page. To achieve this, I created a function called questionsCtrl and I am calling this function in the config while setting up ...

Encountered an error while loading resource: server returned a 500 status (Internal Server Error) - A NodeJs Express and MongoDB Web Application hit a snag

I am currently in the process of developing a web application using NodeJS Express and MongoDB. However, I have encountered an issue while attempting to implement AJAX functionality to load and display comments on the post page. The "post-detail" page is ...

Managing Nested Elements in State in ReactJS

Check out the code snippet below: import React,{useState} from 'react' const iState ={ Name : '', Email :'', Salary :0, Error:{ EName:'*', EEmail:'*', ESalary:'* ...

Cross-Domain Image Uploading

I've been attempting to enable image uploads from one domain to another (CORS). Everything runs smoothly on Localhost, but when I try it on an actual domain, I consistently encounter this message in the Developer Console: Invalid request In my uplo ...

Vue-based bot for telegram web application

Hey there, I've been working on integrating a web app with my chat bot, taking advantage of the new Telegram feature. Unfortunately, after adding the site, I'm encountering an issue where clicking the button opens up an empty page. It seems that ...

The default value is not displayed in the Angular dropdown menu

When using regular html select menus, if you create an option element with selected and disabled attributes and provide text for that option, the text will be displayed by default in the select menu. Below is a basic example of HTML code: <select name= ...

How can I deliver assets in React without the PUBLIC_URL showing up in the path?

I have set up a portfolio website that includes my resume. I am trying to make it so that when someone visits the route http://localhost:3000/resume.pdf, they can view my resume directly. The resume.pdf file is located in my public folder. However, instead ...

Is there a way to navigate to another page once the Facebook.streamPublish() function has finished executing

I am currently facing a challenge with my application where I am able to successfully post a message on a friend's wall using the Facebook.streamPublish() method. However, I also need to save certain details about this post in my database. After send ...

Extract the td elements from a table with specific class using the DataTable plugin

I stumbled upon this snippet of code while browsing through the DataTable website. var table = $('#example').DataTable(); table.column(0).data().each(function(value, index) { console.log('Data in index: ' + index + ' is: &apos ...

What is the most effective way to retrieve distinct values in Mongoose?

I am looking to extract unique values from a collection. Here is an example: const userID = `user1`; const users = await Chat .find({'$or': [{to: userID}, {from: userID}]}) .select(`-_id to from`) .lean(); // users will contain: [ {from: ...

The step-by-step guide on displaying API choices in an Autocomplete feature and keeping them up

Having trouble with updating autocomplete options. An error message pops up in the console log when I try to deselect a tag or select a new one: MUI: The value provided to Autocomplete is invalid. None of the options match with [{"catName":{&qu ...

What causes the parent element's click event to trigger on its own when a child textbox is clicked or focused in Safari?

Describing my HTML setup [Checkbox] [Text] [Input element (Display if check-box is marked)] <span class='spGrpContainer'> <label id='stepGH_Group1' class='lblStep GHSteps lblGroupheader' stepid='1' st ...

Modifying React routes does not alter the path or outlet of the routes

On the app.js file, I have the following routes: import React from "react"; import Login from "./pages/Login"; import { BrowserRouter, Routes, Route } from "react-router-dom"; import Dashboard from "./pages/Dashboard" ...