Creating multiple instances of an object

When using Javascript, I am trying to create an object in the following way:

var testObject = {
    value: "this is my initial value",
    setup: function() {
        value: "foo"
    }
};

Now, my goal is to instantiate this object and have different values for each instance. Here is what I have tried:

var myFirstObject  = new testObject();
var mySecondObject = new testObject();

Unfortunately, when calling .setup(), the value does not change as expected only for that specific object. How can I make this work properly?

Answer №1

Instead of instantiating objects, you should be instantiating functions.

var testObject = function() {
  this.value = "this is my initial value";
  this.setup = function() {
    this.value = "foo";
  }
}

var myFirstObject = new testObject();
var mySecondObject = new testObject();

UPDATE: In response to your comment, here is an example of how to bind to the DOM using functions within the object:

document.getElementById('idOfElem').addEventListener(
    'click', myFirstObject.clickHandler);

Keep in mind that there is no guarantee that the click handler will be executed within the context of your object (meaning that in your click handler, this may not refer to your testObject instance). If your clickHandler needs to modify the object's instance variable in any way, it is recommended to ensure the context like this:

document.getElementById('el').addEventListener('click', 
    function() { 
        myObj.handleClick.apply(myObj, arguments);
    });

Answer №2

Your code has several issues that need to be addressed. Firstly, attempting to instantiate something by calling a constructor function with your testObject will result in a type error since it is not a function. To fix this, the testObject should be defined like this:

var TestObject = function () {
    this.value = "this is my initial value";
};
TestObject.prototype.setup = function () {
    this.value = "foo";
};

It's important to note the use of an uppercase T for the constructor function and how the setup method is defined on the prototype, which is more memory efficient compared to defining it as a property of the instance.

Now that TestObject is a valid function, you can create instances using the new operator:

var myFirstObject = new TestObject();
var mySecondObject = new TestObject();

By calling the setup method on an instance of TestObject, the changes will only apply to that specific instance because the value of this inside the method refers to the calling instance:

myFirstObject.setup();
console.log(myFirstObject.value); // 'foo'
console.log(mySecondObject.value); // 'this is my initial value'

Answer №3

Your constructor definition needs some correction. Consider the following revised code:

function createObject() {
    this.data = "default value";
    this.initialize = function() {
        this.data = "bar"
    }
};

To create an instance of this object, use new createObject().

Answer №4

When using object notation, it is similar to working with a static class concept. Below is the code snippet that demonstrates what you are trying to accomplish:

var testObject = function(val) {
    this.value = "This is my initial value",

    if (arguments[0]) {
        this.value = val;
    }
};

var first = new testObject(); //uses initial value
var second = new testObject("hi"); //value = hi

If you are interested in creating classes using this notation, check out: http://ejohn.org/blog/simple-javascript-inheritance/

Answer №5

function createCustomObject(data, configuration) {
        return {
            data: data,
            configuration: configuration
        };
}

var objectOne = new createCustomObject('alpha', function(){});
var objectTwo = new createCustomObject('beta', function(){});

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

AdjustIframeHeightOnLoad is undefined. Please define it before use

I've noticed that a few of my website pages are loading very slowly. After checking Google inspect (console), it seems like the issue is caused by this error: Uncaught ReferenceError: AdjustIframeHeightOnLoad is not defined. This specific piece of co ...

Utilizing PHP variables to dynamically assign names to radio input tags, and then extracting their values using jQuery or JavaScript

I am facing an issue with my PHP file that generates radio buttons based on unique pets ids. The variable $idperro is constantly changing to distinguish the set of radio buttons. My goal is to insert the value inside the p tag. Here's the PHP code sn ...

Is there a way to eliminate the transform style from a draggable element?

I am looking to enhance the CDK drag and drop example by adding a preview of the dragged element with specific left and top positions, without utilizing the transform style. HTML <div class="example-boundary"> <div class="example- ...

Convert JSON data into an HTML table using JavaScript without displaying the final result

I need help troubleshooting my JavaScript code that is supposed to populate an HTML table with data from a JSON file. However, the table remains empty and I can't figure out why. Sample JSON Data [{"User_Name":"John Doe","score":"10","team":"1"}, { ...

Adjust the number of columns based on the minimum screen resolution using columnizer

Currently, I am utilizing the columnizer jQuery plugin to divide my content into columns on a responsive website with a fluid width container. I have implemented different JavaScript functions based on the minimum screen resolutions, similar to CSS media q ...

Create a gulp task within a callback function that is initiated by calling the filesystem.readdir

When attempting to read the name of the first folder from a directory, and then defining gulp tasks based on that folder, I am encountering an issue. Specifically, after defining a task inside the callback function, the tasks do not get properly defined. T ...

Timing of Vue mounting and initialization phases

I am currently working on a component where I pass the reference to an internal element to the parent using defineExpose. In this example, I simply log the element, but in my actual project, I intend to manipulate it. SFC Playground // Comp.vue <scrip ...

showing console logs before initializing preferences may lead to inaccurate results

My Content Management System (CMS) is WordPress. Recently, after making some changes, I encountered an error on a specific page: An error occurred: loading pref showConsoleLogs before prefs were initialised, leading to incorrect results being displayed - ...

Leveraging React's useEffect hook to asynchronously fetch and load data

In my coding scenario, there is a parent component containing a child component which loads data asynchronously. This is what I currently have: <Parent> <AsyncChild data={props.data} /> <Child /> </Parent> Within the AsyncChil ...

Access arrays/objects within main object using JavaScript's Object.keys()方法

Perhaps the title is a bit confusing, but I couldn't come up with a better way to phrase it. I have a function that determines the value of each property within a contact object and returns 'No Data' if the value is null/empty/undefined. Ho ...

Vanishing Tooltip following an implementation of the backdrop-filter

I'm having an issue with the blur effect on my background image. Although it works well, my tooltips also end up being blurred behind the divs: https://i.stack.imgur.com/BMdh4.png Is there a way to ensure that my tooltips stay on top of the subseque ...

The function d3.geoStitch has not been defined

I am currently working on implementing this example that visualizes a TIFF file using d3 as a node script. Everything seems to be functioning well, except when it comes to d3.geoStitch where my script throws an error stating d3.geoStitch is undefined. The ...

Inconsistent Functionality of Bootstrap Popover

I am experiencing an issue with the bootstrap Popover feature. It seems to work inconsistently - sometimes it works and other times it doesn't. I am using it to create a popover that displays a user's information when a visitor hovers over the us ...

I aim to continuously refresh a dynamic canvas line chart with JSON data

Having trouble with my code - the chart isn't updating. I'm new to using canvasJS charts and could use some help. <%@ page language=”java” contentType=”text/html; charset=UTF-8″ pageEncoding=”UTF-8″%> <%@ page import=”java ...

Unusual Type Inference in Typescript {} when Evaluating Null or Undefined

Upon upgrading from typescript 4.9.3 to 5.0.2, we encountered an error when asserting types. Can someone explain why the function "wontWorking" is not functioning correctly? I expected this function to infer v as Record<string, any>, but instead it ...

Limit the text input area in HTML to a fixed size, preventing any text from exceeding the specified boundary

Is there a way to create a fixed line text area that limits the user from typing beyond a certain number of lines and maximum width? My current CSS styling for this is as follows: .area-style { resize: none; width: 324px; height: 200px; m ...

Trouble arises when incorporating a new feature onto a map with OpenLayers and Vue.js

I'm currently working on integrating a custom control into my map using OpenLayers with Vue.js. The Explore.vue component is responsible for creating the "map" (olmap) with OL, and I bind it to the child component LeftSideBar2.vue. However, when att ...

Create separate arrays for the names and values when returning JSON

Suppose I have a JSON object like this: { "ID": 100, "Name": "Sharon", "Classes":{ "Mathematics": 4, "English": 85, "Chemistry": 70, "Physics": 4, "Biology" ...

Ways to implement the React.FC<props> type with flexibility for children as either a React node or a function

I'm working on a sample component that has specific requirements. import React, { FC, ReactNode, useMemo } from "react"; import PropTypes from "prop-types"; type Props = { children: ((x: number) => ReactNode) | ReactNode; }; const Comp: FC< ...

The token endpoint in Nuxtjs auth module's configuration for auth strategies is not being triggered

Our system has two important endpoints, namely /auth and /token. The endpoint /auth is responsible for providing the authorization code required to call /token in order to obtain an access token. The utilization of NuxtJS has made the auth module a prefer ...