Hello folks!
I am building a library using proposal-decorators
I want to retrieve the parent of a class in argument
Could someone help ?
18 messages · Page 1 of 1 (latest)
Hello folks!
I am building a library using proposal-decorators
I want to retrieve the parent of a class in argument
Could someone help ?
@night relic Here's a shortened URL of your playground link! You can remove the full link from your message.
Preview:```ts
function logger(classArg: Function) {
console.log(
classArg.name,
// 'classArg.parent'
)
}
/**
/**
/**
I have no idea about all this, but I found this: https://stackoverflow.com/questions/43912168/typescript-decorators-with-inheritance
which seems to solve this problem
@night relic Object.getPrototypeOf(classArg).name
Thanks for this link, will dig into it !
And thanks for this snippet, it worked 👍
Do you know why Object.getPrototypeOf(classArg).name is not the same as classArg.prototype.name ?
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)
I still don't grasp their difference enough, I think
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
@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
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 whatObject.getPrototypeOf(x)returns. It's also available asx.__proto__but this syntax isn't preferred (it was originally a non-standard syntax)