Best practice for accessing a JavaScript property within another property

I've been working on an angular project and I've created a factory that provides global database methods. I decided to test it out in a jsfiddle to see if it's the right approach.

If you're interested, here's the link to the jsFiddle.

function DB () {
return {
    newRecord: function () {
         //create new record
        var id = 3;
        //this is the part I am wondering about
        //is it ok to use this in this way??
        this.setCurrentRecordId(id);
    },

    setCurrentRecordId: function (id) {
        alert('setting id');
         return localStorage.setItem('id', id);  
    },

    getCurrentRecordId: function () {
        return localStorage.getItem('id');
    }
}
}

var dbStuff = new DB();

dbStuff.newRecord();

alert(dbStuff.getCurrentRecordId());

While everything seems to be functioning correctly, I'm curious to know if there might be a more efficient way to achieve the same result.

Thank you!

Answer №1

When working with constructor functions in JavaScript, the traditional approach is as follows:

function Database () {
    this.newRecord = function () {
        var id = 3;
        this.setCurrentRecordId(id);
    };

    this.setCurrentRecordId = function (id) {
        alert('setting id');
        return localStorage.setItem('id', id);  
    };

    this.getCurrentRecordId = function () {
        return localStorage.getItem('id');
    };
}

var dbInstance = new Database();

dbInstance.newRecord();

alert(dbInstance.getCurrentRecordId());

If you encounter a situation where the context is lost, such as when referencing the instance in a callback, there are two common solutions.

The first option is to store a reference to `this`:

function CustomCtor(){
    var self = this;
    this.getSomething = function(id){
        asyncTask(id).then(function(result){
            self.doSomethingWith(result);
        });
    };
    this.doSomethingWith = function(result){
        // handle result
    };
}

Alternatively, you can use .bind() to set a specific context for a function:

function CustomCtor(){
    this.getSomething = function(id){

       var processResult = function(arg){
           this.doSomethingWith(arg);
       }.bind(this);

        asyncTask(id).then(processResult);
    };
    this.doSomethingWith = function(result){
        // handle result
    };
}

Answer №2

Utilizing local storage eliminates any potential issues.

function DataStorage () {
return {

    setRecordId: function (id) {
        alert('setting id');
         return localStorage.setItem('record_id', id);  
    },

    getRecordId: function () {
        return localStorage.getItem('record_id');
    }
}
}

var dataStorage = new DataStorage();

dataStorage.setRecordId(5);
dataStorage.getRecordId() // 5

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

Utilizing the Aladin Lite application within a React application, despite not being specifically designed for React

I am interested in incorporating the Aladin Lite app into my React application. Typically, embedding the app in a div is straightforward when developing a website without React: <!-- include Aladin Lite CSS file in the head section of your page --> ...

Exploring the utility of promise.race()

When it comes to promise, there are two main options that I am aware of: promise.all() promise.race() I have a good grasp on what promise.all() does. It runs promises simultaneously, and upon successful resolution, the .then method provides you wit ...

Configuring Google Chart LineChart settings by utilizing the series attribute

I am looking to modify the options for my line chart. However, when I define the options as shown below, the first series setting gets ignored and only the second series property is applied. var options = { title: 'Temperature Graph ( sampling ev ...

Instead of uploading multiple files at once, allow users to upload individual files by clicking on the table row

In my dynamic table, there are 4 columns. The first 3 columns in each row have an input type='file' where users can choose a file to upload, and the 4th column has a submit button aligned with the rows. While submitting files in the first row wor ...

Pass JSON data from Laravel to Controller

Recently I started using Laravel 5 and I'm encountering an issue with sending Ajax json data from the view to controller. Here is my routes.php : Route::post('ticket','TicketController@store'); Route::get('ticket', &a ...

Does React trigger a re-render when setState is called even if the state value remains unchanged?

Imagine I create a React component with an initial state of {random: 1}. Now, if I were to execute the following code: this.setState({random: 1}) Would this action result in triggering a re-render of the component? Furthermore, is there a method to avoid ...

Searching for a Mongoose Model by utilizing a field from a separate Schema

Let's say I have two schemas - User and Post. User schema includes an array of post _ids, and the Post schema has an attribute indicating if it is an active post, labeled as is_active. So, the goal is to filter Users who have at least one active post ...

Alternative method of encapsulating a JavaScript function within a Python environment in a Jupyter notebook

When using an IPython Jupyter notebook, JavaScript functions can be added using the %% javascript magic cell syntax or with the Python kernel using IPython.display.HTML. Python variables can also be modified in JS using IPython.notebook.kernel.execute. It ...

Should objects passed as props be modified in Vue.js components?

I've observed that in Vue, object fields passed as Props can be changed, and these changes reflect in the parent component. Is this considered a bad practice? Should it be avoided, or is it acceptable to use? What are the potential pitfalls of this a ...

Ways to incorporate conditional logic with URL query parameters in Next.JS

I'm trying to implement conditional logic based on a URL query. In this scenario, I want to greet Kátia Fantes dynamically when she visits localhost:3000/katia-fantes. Any suggestions on how to achieve this? import { useRouter } from 'next/rou ...

Exploring the World of D3.js with an Interactive Example

Struggling to grasp D3, I'm having difficulty executing the circle example. http://mbostock.github.com/d3/tutorial/circle.html I aim to run the part where the circles change colors and sizes. I simply copied and pasted the example but can't fi ...

Discovering terms in JavaScript

Looking at a sorted array like this: var arr = [ "aasd","march","mazz" ,"xav" ]; If I'm searching for the first occurrence of a letter that starts with "m", how can I achieve it without iterating through the entire array? ...

What is the best way to create a sharp light effect on a sphere in three.js?

My three.js scene features a sphere and directional light. The sphere appears to gradually darken as you look at it. How can I speed up the transition from light to dark? Is there a way to make the light appear "sharper"? var scene, camera, renderer, co ...

I am looking to share videos and large files without the use of a flash plugin

Looking for a way to upload videos without using the Flash Plugin and without relying on the browser's default browse button, especially for large files. It would be great to have a progress bar displayed during the upload process. Alternatively, is ...

Is the Javascript event firing being hindered by the data object in the Meteor template?

Encountered an unusual issue in Meteor... A function is used to render a template and append it to a div. Within the added template, there's a button that triggers listener events. The odd thing is that the click event can be triggered when renderin ...

The useEffect function is repeatedly making API calls within a component, despite not having any dependencies specified

As a newcomer to React.Js, I'm encountering an issue with useEffect repeatedly calling an API without any specified Dependency. Is there another approach I should consider? The relevant file is located at: /pages/dashboard/speaking/[slug].js } else i ...

Apply an overlay to the entire body while excluding a specific element

Styling with CSS .myoverlay { position: absolute; background-color: rgba(0, 0, 0, 0.7); top: 0; left: 0; bottom: 0; right: 0; opacity: 0.5; } Structuring ...

The Vue 3 composition API does not allow for the return of values from helper functions to components

It seems that there may be a scope issue within my helper function. I have successfully implemented the same logic in my component and it works flawlessly. I have already utilized a composable function to incorporate ref() with the variable that needs to ...

Sending data from HTML and JavaScript to Python

In the process of developing a website that will operate on an embedded device, I am implementing an interface for users to engage with multiple functions on the site. These functions within the HTML interface will communicate with a Python script, which i ...

Submitting a form across controllers in AngularJS: What you need to know

<div ng-controller="ctrl1"> <form name="form1" ng-submit="submitForm()"> <input type="text" name="email" /> </form> </div> <div ng-controller="ctrl2"> <button> Submit </button> </div&g ...