Enhancing TypeScript - Managing Variables within Namespace/Scope

Why is the console.log inside the function correctly logging the object, but after the function returns it logs undefined, failing to update the variable?

In addition, when using this within testNameSpace, it returns window. Why is that?

namespace testNameSpace {

    let settings: any;

    function dtJSONLoad() {
        let xobj = new XMLHttpRequest();
        xobj.overrideMimeType("application/json");
        xobj.open('GET', './js/file.json', true);
        xobj.onreadystatechange = function () {
            if (xobj.readyState == 4) {
                let response = xobj.responseText;
                settings = JSON.parse(response);
                console.log(settings);
            }
        };
        xobj.send(null);
    }

    dtJSONLoad();
    console.log(settings);

}

The first console log outputs 'undefined'

The second console log shows the returned object

Answer №1

Two common issues frequently discussed on SO (especially those tagged with TypeScript) are presenting themselves to you.

The first problem arises when you perform an asynchronous operation like so:

dtJSONLoad();
console.log(settings);

Your console.log statement is running before the completion of the dtJSONLoad, resulting in the settings variable being undefined.
The second console.log reflects the true value upon the async operation's completion.

The issue also involves the scope of this:
When assigning a function to xobj.onreadystatechange, that function does not correspond to the current this, causing it to point to the Window object upon execution.
There are two ways to address this:

(1) Employ an arrow function to retain the existing scope of this:

xobj.onreadystatechange =  () => {
    // ...
};

(2) Utilize the Function.prototype.bind method:

xobj.onreadystatechange =  function () {
    // ...
}.bind(this);

Edit

In a namespace, the concept of this doesn't apply due to its compilation into javascript.
For instance, consider this scenario:

namespace mynamespace {
    console.log(this); // Error: 'this' cannot be referenced in a module or namespace body
}

This results in:

var mynamespace;
(function (mynamespace) {
    console.log(this);
})(mynamespace || (mynamespace = {}));

An equivalent method would involve:

function fn() {
    console.log(this);
}

In both cases, this points to the Window object.

If you modify it as follows:

namespace mynamespace {
    export function fn() {
        console.log(this);
    }
}

mynamespace.fn();

You'll observe the output as: Object {}, which is accurate because the fn resides within mynamespace.
Here's how it appears in JavaScript:

var mynamespace;
(function (mynamespace) {
    function fn() {
        console.log(this);
    }
    mynamespace.fn = fn;
})(mynamespace || (mynamespace = {}));

Answer №2

Upon initial logging, the data is not yet present.

The data only appears during the callback on the second attempt, shortly after the request is initiated for the first time.

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

Generating a three-level unordered list using arrays and for-loops in JavaScript/JSON

Are there more efficient ways to achieve the desired results from this JSON data? Can someone assist me in understanding why it is working and if it can be optimized for cleanliness? <div id="accordion" class="display-data"> ...

Struggling to make the grunt.js task for postcss with autoprefixer function properly

I am currently facing issues with using postcss in conjunction with autoprefixer-core. Even though the css is being generated correctly, autoprefixer doesn't seem to be applying any prefixes. I have already installed postcss and autoprefixer via NPM ...

Is there a way to simulate a click event within a Jasmine unit test specifically for an Angular Directive?

During the implementation of my directive's link function: $document.on('click.sortColumnList', function () { viewToggleController.closeSortColumnList(); scope.$apply(); }); While creating my unit test using Jasmine: describe(&apo ...

Arrange fixed-position elements so that they adhere to the boundaries of their adjacent siblings

Is there a way to keep two fixed elements aligned with their sibling element on window resize? <div class="left-img"> IMAGE HERE </div> <!-- fixed positioned --> <div class="container"> Lorem ipsum... </div> <div class=" ...

Multiple onClick events being triggered unexpectedly upon component re-render

My react component is a form that triggers a function to handle data saving and other tasks when the send/submit button is clicked. The issue arises when the component seems to re-render multiple times after the button click, most likely due to updated ex ...

Why is my root page not dynamic in Next.js 13?

I am currently working on a website using Next.js version 13.0. After running the next build command, I noticed that all pages are functioning properly except for the root page. The issue is that it's being generated as a static page instead of dynami ...

Enhancements to a NativeScript Application

After running some tests on my NativeScript app following the steps outlined here - , I found that it takes 18 seconds for the program to start and for a user to log in. Is this considered acceptable performance? Appreciate any feedback provided! ...

What could be causing npm to fail to launch?

Whenever I execute node app.js, my server functions perfectly. However, when attempting to utilize nodemon for running the server, it fails to start. The error displayed by npm start is as follows: npm ERR! code ELIFECYCLE npm ERR! errno 9009 npm ERR! < ...

The server's file URLs are modified within the page source of a WordPress site

I've been attempting to integrate Adsense code into a WordPress blog at demonuts.com. I placed the Google code in the TEXT WIDGET provided by WordPress. However, upon running the website, I noticed that the URLs for .js, .css, or .png files are being ...

Struggling to retrieve JSON data from a URL and unsure how to manage errors and exceptions

Currently, I am attempting to retrieve JSON data from a specific URL within an Android application. The URL in question solely contains JSON information with no additional content. At this time, my main objective is to fetch the contents of the URL and sto ...

Identify a CSS style or attribute that is being dynamically assigned using JavaScript

While using the Jquery Cycle plugin for my slideshow, I'm looking to trigger an event when a specific slide is active. The Cycle plugin handles this by adjusting the opacity of images within a div in this manner: <div style="position: absolute; to ...

How do I redirect with a GET method after calling the *delete* method in Node / Express server?

As someone new to AJAX and Node, I encountered a dilemma that I hope to get some guidance on. Here's the issue: I have a DELETE ajax call that removes a row from the database and I want to redirect back to the same route with a GET method afterwards. ...

Choose a row from a table by utilizing AJAX with jQuery

Need help with deleting specific table rows using AJAX? The goal is to send the ID and Printer Type values from the table data cells when a row is selected for deletion. <table class="u-full-width" > <thead> <tr> ...

Is there a callback or event that can be used to ensure that getComputedStyle() returns the actual width and height values?

Currently, I find myself in a situation where I need to wait for an image to load before obtaining its computed height. This information is crucial as it allows me to adjust the yellow color selector accordingly. Question: The process of setting the yello ...

Can we verify if strings can serve as valid property names for interfaces?

Let's consider an interface presented below: interface User { id: string; name: string; age: number; } We also have a method defined as follows: function getUserValues(properties:string[]):void { Ajax.fetch("user", properties).then( ...

Attempting to transform HTML code received from the server into an image, but encountering an error while using ReactJS

This app is designed to automate the process of creating social media posts. I have a template for the vertical "Cablgram" stored in the backend, and when I make a request, it returns the HTML code for that template. However, I encounter an error when tryi ...

Is it possible to display CKEditor5 toolbar buttons in a separate row rather than the primary row?

https://i.stack.imgur.com/Tyfqb.png I successfully integrated CKEditor5 into my create react app directly from the source code. However, I am facing an issue where the overflowed buttons in the toolbar are being displayed in a separate menu item instead o ...

Unique Tags and Javascript: A customized approach

In the process of developing a web application, I am aiming for high standardization. To achieve this goal, I plan to utilize custom namespace tags that will be modified by JavaScript based on their functionality. For instance: <script type="text/java ...

Switch the selected option in JQuery UI dropdown using a clickable button

I have a code snippet that is almost working. My goal is to change the selection of a JQuery dropdown select combobox using a separate button named "next". What I want is for the JQuery dropdown to automatically switch to the next selection every time I c ...

Obtain the outcome of HTML5 FileReader by utilizing promises within an asynchronous function

I am encountering a challenge in my Angular 4 application where I am working with an image. I am trying to pass the base64 string to another variable, but due to the asynchronous nature of this process, the image.src ends up being empty. As a result, the ...