edison
edison

Reputation: 13

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

why this is not Person(class)but is a Persson(constructor) Why is it possible to use one class to inherit constructors from another class in Typescript?

function Name(constructor: Function) {// !!!!! why this is not Person(class)but is a Persson(constructor)
  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 this is not Person(class)but is a Persson(constructor) in Function Name

Upvotes: 1

Views: 42

Answers (1)

cyco130
cyco130

Reputation: 4944

This is not TypeScript specific, it is related to how JavaScript works. Classes are just functions.

Classes are a new feature that are part of the ECMAScript 6 standard (from 2015). It's mostly just syntactic sugar for an established JavaScript pattern for emulating classes. The following code:

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

does almost the same thing as this:

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

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

As you can see, JavaScript classes are just functions! But what does it mean and how does it work?

The answer is this: Every time you call a JS function, a hidden this parameter is passed to the function:

  • When you call a function by itself (myFunction()), this is the global object (usually window on browsers).
  • When you call a function with the dot notation (myObject.myFunction()), this is set to your object (myObject).
  • When you call a function with the new keyword (new myFunction()), a new object is created and this is set to this new object.

There is one more thing: the prototype. In JS objects have a property called the prototype. When you use the dot notation, if the object doesn't have the requested property, it's looked up in the prototype. If it can't be found there, it's looked up in the prototype's prototype and so on. The new func() syntax sets the newly created object's prototype to func.prototype. So when you write:

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

the print method is looked up in myObject and since it isn't there, it's looked up in MyClass.prototype.

This prototype based flavor of OOP is very flexible but it became a source of confusion for programmers coming from class based languages. Several libraries were written to simulate classes. And finally they were added to the language in 2015.

This is the reason why a class is actually just a function in JavaScript.

Upvotes: 1

Related Questions