What allows for the inheritance of constructors from one class to another in Typescript?

Why is it possible to have one class inherit constructors from another class in Typescript?

function Name(constructor: Function) {
  return class Name extends constructor {
    name = 'genal';
  }
}


@Name
class Person {
  constructor() {
    this.type = 'yellow';
  }
}

console.log(new Person());

output: Name{ type: 'yellow', name: 'genal' }

// Why does the function output refer to Persson(constructor) instead of Person(class) in the Name function?

Answer №1

Understanding JavaScript classes is not limited to just TypeScript; it delves into the core workings of JavaScript itself. Essentially, classes in JavaScript are nothing more than functions.

Introduced as part of the ECMAScript 6 standard in 2015, classes are primarily a syntactic sugar that simplifies an established JavaScript practice of mimicking classes. For instance, the following code snippet:

class MyClass {
  constructor(myProp) {
    this.myProp = myProp;
  }
  
  print() {
    console.log(this.myProp);
  }
}

achieves similar functionality as this:

function MyClass(myProp) {
  this.myProp = myProp;
}

MyClass.prototype.print = function () {
  console.log(this.myProp);
};

JavaScript classes essentially boil down to being functions. But how exactly does it all work?

The fundamental idea is this: every time a JavaScript function is called, a hidden this parameter is passed to the function:

  • Calling a function by itself (myFunction()) sets this to the global object (typically window on browsers).
  • Using the dot notation while calling a function (myObject.myFunction()) assigns this to the respective object (myObject).
  • Invoking a function with the new keyword (new myFunction()) entails creating a new object and setting this to point to the newly created object.

Additionally, there's the concept of prototypes in JavaScript. Objects in JS have a property known as the prototype. When utilizing the dot notation, if the requested property isn't found in the object, it's then sought after in the prototype. If still not found, the search continues up the prototype chain. The new func() syntax aligns the prototype of the freshly created object with func.prototype. Therefore, when you write:

var myObject = new MyClass("propValue");
myObject.print();

the print method is first searched for within myObject and then in MyClass.prototype.

This prototype-based approach to OOP offers great flexibility but has often been perplexing for programmers accustomed to class-based languages. To mitigate confusion, numerous libraries were developed to mimic classes, eventually paving the way for their official integration into JavaScript in 2015.

Hence, the essence of why a class is essentially just a function in the realm of JavaScript.

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

Entering information into fluctuating object fields

Suppose I have a dynamic object with a union type: data: {[key in 'num' | 'str' | 'obj']: number | string | object}; I set the object properties as follows: data.num = 1; data.str = 'text'; data.obj = {}; E ...

Tips for transferring Google Maps place array data from Angular 5 TypeScript to HTML

I am new to Angular 5 and I am attempting to display nearby restaurant results using Google Maps in Angular 5. However, I am unsure of where to create the array in TypeScript and how to pass this array into the HTML when searching for "restaurant". I have ...

A guide on extracting all floating-point numbers from a string in Java

I have a unique string: Data Point, x: 0.0 y: -0.9980941 Data Point, x: 1.0 y: -0.9686125 Data Point, x: 2.0 y: 0.9044667 Is there a way to extract all decimal values using regex? 0.0, -0.9980941, 1.0, -0.9686125, 2.0, 0.9044667 ...

What sets JSON arrays apart from JSON objects?

What distinguishes the use of JSON arrays from JSON objects and what are their respective advantages? { arrayExample:[ { /* items */ }, { /* items */ } ] } Vs. { objectExample:{ { /* properties */ }, { /* properties */ } ...

Algorithm in Javascript that identifies the larger number that matches the given input

I recently encountered a logic problem that involved comparing an input variable with an array to find the smallest number in the array without using sorting. For example, I had an array like: const arr = [20,25,13,10,3,5,9,22]; and an input value of: var ...

Arranging the y-value array based on the x array in ascending order using Python

If I have two arrays like this: x = [0, 7, 2, 4, 6, 9, 5] y = [1, 2, 3, 4, 5, 6, 7] With data points at coordinates such as [0,1], [3,2], and [x_n,y_n]. How can I organize array y so that it corresponds to an ascending order of x values? Meaning the x v ...

"Utilizing variadic tuple types to implement the pipe function in TypeScript 4: A step-by-step guide

An illustration from the release notes of TypeScript 4 demonstrates the use of variadic tuple types to eliminate multiple overload definitions. It seems feasible to type the pipe function for any number of arguments. type F<P, R> = (p: P) => R ty ...

The JSON array object gets replaced in the local storage

I have been working on a form page where there are 3 input fields: "fname," "emailId," "phoneNo." Every time a user enters details in the form, I am storing them in localStorage. However, the object keeps getting overwritten. Here is the script: <scri ...

I am looking to retrieve a specific array element record from an array within a MongoDB document using the MongoDB Java API

Within a single document, I have an array with various elements. My goal is to extract specific values from this array. { "_id" : ObjectId("54a67aa569f2bc6a5865f220"), "language" : "us_english", "country" : "united states", "state" ...

Retrieve PDF files from .Net Core Web API using Angular

I've been struggling with this issue for several days now. Despite searching through many threads on Stackoverflow, I couldn't find a solution that worked for me. Below is the Web API code meant to return a simple PDF file: [HttpGet("pd ...

Discover the indexes within an array that include any of the values from a separate array

Is there a way to determine the indices of values within an array (a) that correspond to elements in another array (label) which contains multiple "markers"? For instance, consider the following: label = array([1, 2]) a = array([1, 1, 2, 2, 3, 3]) The ob ...

Outputting information from a multi-level array

I am facing a challenge in looping through an array retrieved from a database and displaying the Field_Name and Field_Value on a webpage. Array ( [0] => stdClass Object ( [Field_Name] => First Name [Field_Value] = ...

Storing arrays using Backendless and Realm

Recently, I've started exploring backendless.com and Realm.io My current task is to create a simple table with categories and associated items I'm facing a challenge retrieving data from backendless as I need to create a class that is compatibl ...

Calculate the total of all subarrays within a key-value array

My array is multi-dimensional and looks like this ... https://i.sstatic.net/xpHeb.png ** Please note that the image does not show closing brackets in the array, so there are no syntax issues. I am trying to sum up the values in each key (Openness, Consc ...

Confirmation in Sweet Alert before deleting an item in Angular 2

Currently, I am facing an issue with my AlertService that uses Sweet Alert. My goal is to confirm whether the user truly wants to delete something before proceeding with the action. Despite utilizing arrow functions and attempting bind(), I am encountering ...

Ruby code for creating an iteration in an ordered array

numbers = [] array = [4,5,6] array.each{|num| numbers.push(num) ; numbers.push(num)} Returns: [4,4,5,5,6,6] Is there a more efficient way to accomplish this in Ruby? ...

Replace array objects nested within a JavaScript array

I am working with an array of sections that need to be dynamically replaced. Each section has a unique section ID. I have a "section" object with an ID, and I need to replace this object within the "sections" array while preserving the values of the rest o ...

lua update/swap 2D array

I'm facing an issue with my array2d. I am looking to implement a refresh command in my code. The data is stored in data.txt test1:30:1 test2:40:2 Whenever I call the ReadData function, it should populate my Array2d like this : line_data = {{"test1 ...

Looking for a way to include an input box within a react-select option dropdown menu

Currently, I am facing a situation where I need to include an input box within my dropdown option menu. The challenge is that I cannot utilize the custom tag creator feature of react select to create a new option with the dropdown. Upon going through the ...

When utilizing Angular 2, this message is triggered when a function is invoked from the Observable

One of my services is set up like this: @Injectable() export class DataService { constructor(protected url: string) { } private handleError(error: Response) { console.log(this.url); return Observable.throw(new AppError(error)); ...