Mastering the art of utilizing class attributes and functions from within modules

Currently, I am developing classes in ES6 modules using object literals and my intention is to update object attributes within a function. Although modules run in strict mode by default which ensures safe usage of this, I am uncertain whether calling the function foo() will modify the object in the main script file or if it only affects the local object within Controller.mjs. Will both function calls produce the same outcome?

//Controller.mjs
const Controller = {
    someAttr1: [],
    someAttr2: true,

    foo: function () {
        this.someAttr1.push("some value");
        Controller.someAttr1.push("some value");
    }
};

//export Controller's interface...

//SomeOtherFile.mjs
import { Controller } from 'Controller.mjs'

Controller.foo();

Answer №1

the item I am accessing in the 'parent' script file or simply the local item that only exists in Controller.mjs

Your code actually only contains one item. The use of the import statement just creates a reference for the const Controller variable from the imported module. There is no creation of a separate, second item.

In terms of whether to use this or Controller to refer to the object, you can check out this resource: Javascript: Object Literal reference in own key's function instead of 'this'. This choice is relevant regardless of whether the code is divided among different modules or not.

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 Node.js callback is executed before the entire function has finished executing

const fileSystem = require('fs'); const filePath = require('path'); module.exports.getFiles = function(filepath, callback) { let files = []; fileSystem.exists(filepath, function(exists){ if(exists){ fileSy ...

Verify the presence of the promotion code and redirect accordingly

I have created a special promotion page that I want to restrict access to only users who have received a unique code from me via email. To achieve this, I have designed the following form: <form accept-charset="UTF-8" action="promotion.php" method="po ...

What is the reason behind the browser not reusing the authorization headers following an authenticated XMLHttpRequest?

As I work on developing a Single Page Application using Angular, I have encountered an interesting challenge. The backend system exposes REST services that require Basic authentication. Surprisingly, while obtaining index.html or any of the scripts does no ...

Exploring the versatility of combining CSS classes with MUI 5 SX prop

Is there a way to use multiple CSS classes with the MUI 5 SX prop? I've defined a base class for my Box components and now I want to add a second class specifically for styling the text inside the Box. When I try to apply both classes like sx={styles. ...

The `Target closed` error in Playwright Library is triggered solely by the closing of either the `context` or `browser`

The code snippet below showcases a Node.js script that leverages the Playwright Library for browser automation (not Playwright Test) to extract data from a local website and display the results in the terminal. The challenge arises when the script encounte ...

Freezing objects using Object.freeze and utilizing array notation within objects

Could someone kindly explain to me how this function operates? Does [taskTypes.wind.printer_3d] serve as a method for defining an object's property? Is ["windFarm"] considered an array containing just one item? Deciphering another person& ...

What could be the reason for the handleOpen and handleClose functions not functioning as expected?

I am facing an issue with my React component, FlightAuto, which contains a dropdown menu. The functionality I'm trying to achieve is for the dropdown menu to open when the user focuses on an input field and close when they click outside the menu. Howe ...

Tips for achieving comma-separated user input via ngModel and appending it to an array

I am working on an email template that includes a cc option. I want users to be able to add email addresses with commas separating them and then push them to an array called $scope.notifyCtrl.cc. How can I accomplish this using AngularJS 1.5 and above? mai ...

Issues with setSelectionRange functionality in JavaScript unit tests leading to unexpected behavior

Currently, I am utilizing the qunit framework to perform unit testing on interactions within an HTML element that has been dynamically created using jquery (specifically, var $textarea = $('')) in Chrome. Below is the code snippet I am employing ...

Separating screens for logged in and logged out users in React Router with Firebase is not possible

I'm currently developing an application using React and Firebase. The app has a requirement for user authentication to access their own timeline. To achieve this, I have decided to split the app into LoggedIn screens and LoggedOut screens. In the App ...

Developing an intricate nesting structure for an object

this is my code snippet: "book" => {b:{o:{o:k:{'end':true} could someone please provide an explanation or a helpful link for this? const ENDS_HERE = '__ENDS_HERE' class Trie { constructor() { this.node = {}; } insert(w ...

How can I dynamically retrieve the width of an image in React as the screen size changes?

I have successfully implemented an image hover effect on my website. When I hover over a certain text, an image appears. The image is responsive, but I am facing an issue where I want the width of the text to be equal to the width of the image. When I resi ...

Tips for prioritizing new data input at the top of the list

Hey there, I'm having trouble figuring out how to push new data to the top of a list using vue.js and laravel. I've been trying but haven't had any luck so far. If anyone could lend a hand, I would greatly appreciate it. Below is my Control ...

Unable to successfully import an external HTML file that contains a script tag

I am currently experiencing an issue with my index.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8> <title>MyApp</title> <link rel="import" href="./common.html"> </head> <body> ...

What is the process of synchronizing state in react.js?

I am struggling to update the state and component in my code. When I press a button and change the value of one of the props in the popup component, the prop value does not get updated. I suspect this issue is due to using setState. I researched a possible ...

Encountered an error while using JSON.parse(): `SyntaxError: Unexpected token in JSON at position 0`

As I embark on my Node.js development journey, I am faced with a challenge while trying to retrieve data from a JSON file. An error message interrupts my progress: SyntaxError: Unexpected token  in JSON at position 0 at Object.parse (native) Below is ...

Is there a specific requirement for importing a React component into a particular file?

I am facing an issue with my component and two JavaScript files: index.js and App.js. When I import the component into index.js, it displays correctly on the screen. However, when I import it into App.js, nothing appears on the screen. Here is the code fr ...

Creating a Python class that can accept a variable number of arguments - How is this achieved?

As a novice in Python programming, I am eager to learn by writing a class that can accept up to 3 different arguments (a, b, c). Here is an example: class CustomClass(object): def __init__(self, a=0, b=0, c=0): # Implement your code here I w ...

Getting the Value from a Promise into a Variable in a React Component

I am currently immersed in a React project where I am utilizing the Axios library to retrieve data from an API and store it in a variable. After scouring the internet, it seems that the only method available is through Promise.then(), but this approach si ...

What is the best way to set checkboxes to default values using a model?

My journey with angular.js continues as I embark on creating my first non-tutorial web app. In this endeavor, I am utilizing two smart-tables and checklist-model for a seamless user experience. The initial table uses a st-safe-src of all_types, containing ...