0

I have a JavaScript code that looks like the excerpt below. At line,

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

will the this scope contain the user instance passed as parameter to the constructor?

I've read this post on this scope, but, according to my belief, at setAdmin this refers to MyClass which does not include (or does it?) the parameters like user passed to 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;
    }
  }
}
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
Serg M Ten
  • 5,568
  • 4
  • 25
  • 48

1 Answers1

2

setAdmin this refers to MyClass which does not include (or does it?) the parameters like user passed to the constructor.

You're right that this is a reference to the instance of MyClass that's currently being constructed. However, since you marked the parameter as public, typescript will put the user on this.user. Marking parameters to a constructor as public (or private for that matter) is a shortcut that typescript provides for assigning the parameters onto the instance of the class.

If it helps, here's what the transpiled version of your code looks like:

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;
});
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98