#Decorators : Retrieving Parent of a Class in Argument

18 messages · Page 1 of 1 (latest)

night relic
#
GitHub

Decorators for ES6 classes. Contribute to tc39/proposal-decorators development by creating an account on GitHub.

mint pendantBOT
#

@night relic Here's a shortened URL of your playground link! You can remove the full link from your message.

malix_off#0

Preview:```ts
function logger(classArg: Function) {
console.log(
classArg.name,
// 'classArg.parent'
)
}

/**

  • expected: "A", none/undefined/""
    */
    @logger
    class A {}

/**

  • expected: "B", "A"
    */
    @logger
    class B extends A {}

/**

  • expected: "C", "B"
    ...```
onyx oracle
#

which seems to solve this problem

swift siren
#

@night relic Object.getPrototypeOf(classArg).name

night relic
night relic
night relic
swift siren
#

prototype gets the prototype of the current object

#

Err, probably not saying that right. If you do User.prototype that's the prototype for User objects.

#
class User {}
User.prototype.name = "Bob";

new User().name; // "Bob"
#

(Not valid TS code but this is how the JS works)

night relic
timber wasp
#

I think User.prototype is the prototype of a User instance

#

Object.getPrototypeOf is the prototype of the current object

#
class Thing {}
class User extends Thing {}
const userInstance = new User

User.prototype === Object.getPrototypeOf(userInstance)
Object.getPrototypeOf(User) === Thing
swift siren
#

@night relic If you really want to get into the nitty-gritty of how inheritance works in JS, you may want to read up on it with something like https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

MDN Web Docs

In programming, inheritance refers to passing down characteristics from a parent to a child so that a new piece of code can reuse and build upon the features of an existing one. JavaScript implements inheritance by using objects. Each object has an internal link to another object called its prototype. That prototype object has a prototype of its...

#

But the core part is that each object (potentially) has a backwards link to a prototype that it shares state with:

JavaScript implements inheritance by using objects. Each object has an internal link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype.
This backwards link is what Object.getPrototypeOf(x) returns. It's also available as x.__proto__ but this syntax isn't preferred (it was originally a non-standard syntax)