Skip to content

Instantly share code, notes, and snippets.

@neroze
Created June 25, 2018 05:05
Show Gist options
  • Save neroze/916e18b0b3f574f9d28073d3f7cfb816 to your computer and use it in GitHub Desktop.
Save neroze/916e18b0b3f574f9d28073d3f7cfb816 to your computer and use it in GitHub Desktop.
A class decorator function
/*
A class decorator function will receive target class UserRef, which is User in above example (on which decorator is applied)
and must return a constructor function. This opens the door of infinite possibilities that you can do with the decorator.
Hence class decorators are more popular than method/property decorators
*/
Ref: https://itnext.io/a-minimal-guide-to-ecmascript-decorators-55b70338215e
function withLoginStatus( UserRef ) {
return class extends UserRef {
constructor( ...args ) {
super( ...args );
this.isLoggedIn = false;
}
setLoggedIn() {
this.isLoggedIn = true;
}
}
}
@withLoginStatus
class User {
constructor( firstName, lastName ) {
this.firstName = firstName;
this.lastName = lastName;
}
}
let user = new User( 'John', 'Doe' );
console.log( 'Before ===> ', user );
// set logged in
user.setLoggedIn();
console.log( 'After ===> ', user );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment