What does 'this' refer to in a JavaScript function that is inside an object?

I'm currently working with a JavaScript code snippet that looks like the example below. On this particular line,

this.orgBusinessKey = this.user.noaOrganisationList[0].businessKey;

I'm wondering if the this scope will contain the user instance that is passed as a parameter to the constructor.

While I have already checked out this article on this scope, but I still have doubts. In my understanding, at setAdmin, does this point to MyClass, which may not include the parameters like user from the constructor?

export interface IUser {
  noaOrganisationList: IOrganisation[];
}

export interface IOrganisation {
    id?: number;
    name?: string;
    businessKey: string;
}

export class MyClass {

  orgBusinessKey: string = '';

  constructor(public user: IUser)
  {
    this.setAdmin(user);
  }

  setAdmin(user: IUser): void {
    if (user && user.noaOrganisationList && !_.isEmpty(user.noaOrganisationList)) {
      this.orgBusinessKey = this.user.noaOrganisationList[0].businessKey;
    }
  }
}

Answer №1

When using setAdmin, it is in reference to MyClass. It's worth noting that MyClass does not explicitly include the parameters like user in its constructor.

It's true that this points to the instance of MyClass currently being constructed. However, by declaring the parameter as public, TypeScript will assign the user to this.user. By marking constructor parameters as public or private, TypeScript conveniently assigns them to the class instance.

If it helps, below is the transpiled version of your code for reference:

define(["require", "exports"], function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var MyClass = /** @class */ (function () {
        function MyClass(user) {
            this.user = user; //  <------------------ SEE THIS LINE
            this.orgBusinessKey = '';
            this.setAdmin(user);
        }
        MyClass.prototype.setAdmin = function (user) {
            if (user && user.noaOrganisationList && !_.isEmpty(user.noaOrganisationList)) {
                this.orgBusinessKey = this.user.noaOrganisationList[0].businessKey;
            }
        };
        return MyClass;
    }());
    exports.MyClass = MyClass;
});

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

What is the reason for the num pad being classified as a character?

Everything is functioning correctly, but when I use the number pad on the right side of my keyboard, it registers as a character and gets deleted. However, the numbers on the left side are accepted without any issue. I want to be able to input numbers usin ...

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 ...

Having trouble retrieving response headers in Angular 5

After sending a post request to a server, I receive a response with two crucial headers for the client: username and access-token. The Chrome debug tool's Network Tab displays the data from the response like this: https://i.sstatic.net/XN9iv.png In ...

Dynamic way to update the focus color of a select menu based on the model value in AngularJS

I am looking to customize the focus color of a select menu based on a model value. For example, when I choose "Product Manager", the background color changes to blue upon focusing. However, I want to alter this background color dynamically depending on th ...

Error: The specified JSON path for Ajax request could not be

Although my expertise lies in C++, I must confess that my knowledge about web development is quite limited. Therefore, please bear in mind that my question requires a simple answer. Recently, I stumbled upon a fascinating C++ library for creating a web se ...

Develop an extensive Typescript and React shared library

Trying to develop a shared React and Typescript library has been quite challenging. Configuring the project workspace to work on both the library and application simultaneously has proven to be more difficult than anticipated. project ├─ app │ ├ ...

The ever-changing world of list items with dynamic editions

One of my tasks involves displaying a list of elements through the ng-repeat directive. Each element is contained within its own div block. My goal now is to enable editing for each block, so that when users click on an edit button, the content of the div ...

Encountering a Node Js post handling error with the message "Cannot GET /url

This is my ejs file titled Post_handling.ejs: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>POST-Handling Page</title> </head> <body& ...

Retrieving a channel using its unique ID and then sending a message directly into it

I am attempting to retrieve a channel by its ID and then send a message to it, but I keep encountering an error when running the code. ERROR: Error sending message to welcome channel.: TypeError: Cannot read properties of undefined (reading 'send&apos ...

JavaScript Tutorial: Storing HTML Text in the HTML5 Local Storage

I am looking to save the text that is appended using html() every time I click on a button. The goal is to store this text in HTML 5 local storage. $('#add_new_criteria').on('click',function(){ $('#cyc_append').html(&apo ...

What is the object pattern in Typescript?

Recently delving into TypeScript, I am eager to learn how to define an interface for the following type of object: const branch = { 'CN': { 'name': 'CN Name', 'branch': 'Chinoise', 'url& ...

How can we send state updates directly to a conditionally rendered React component?

I am currently developing a React application with a tab section that displays specific components upon clicking on a tab. Initially, I have my parent component: class Interface extends Component { constructor(props) { super(props); ...

Determine if the JSON lacks an array within it

Utilizing an API to fetch results, the response received looks something like the following: {"currentPage":1,"numberOfPages":1,"totalResults":1,"data":[{"id":"Sf8xxo","name":"The Bear Reader Huckleberry Oatmeal Stout","nameDisplay":"The Bear Reader Huckl ...

Best practices for implementing localization in AngularJS 1.5.x

Visit this link When working with newer versions of the framework (>=1.4.0), it is recommended to utilize the built-in i18n tools. For older versions (<1.4.0), angular-translate is a suitable option. The documentation provides detailed steps for ...

Obtain the name of the object method from inside the method itself

Imagine having an object like this: var app = {} inside which there is a method: app = { initialize: function () { } } Is it possible to retrieve the name of the method 'initialize' from within the initialize() function without explicit ...

Discovering the method to incorporate a data-icon attribute within select options using vue.js

UPDATE before modification dataIcon: " @/images/flag-ukraine.svg" after modification dataIcon: require("@/assets/svg/flag-ukraine.svg"), notable change with require() I am using Materialize CSS select. When I use a URL for dataIcon ...

Resolving Incompatibility Problems Between Devices

While learning Typescript with React, I have encountered type compatibility issues when converting dates. Below is the content of my data.ts file: import { Result } from "./columns"; export enum Quality { High = "high", Medium = & ...

Is there a problem with the props being passed? Can someone verify this

Blockquote Having trouble passing props, Parent component: props: { data: { type: Object as PropType<FormatOrderItem>, default: () => {} } I'm facing an issue when trying to pass props from the parent component to the ch ...

Bootstrap modal not displaying in full view

I recently ran into some issues while using a jQuery plugin with my bootstrap modal on my website. After implementing jQuery.noConflict(), I encountered a problem where the program no longer recognized $, forcing me to replace all instances of it with jQue ...

Tips for embedding Javascript code within the window.write() function

I have a JavaScript function that opens a new window to display an image specified in the data variable. I want the new window to close when the user clicks anywhere on it. I've tried inserting some JavaScript code within window.write() but it doesn&a ...