Skip to content

🔥 A Php Trait Javascript Equivalent helps you reuse methods in single inheritance languages such as PHP & Javascript.

License

Notifications You must be signed in to change notification settings

regsisabelo/trait.js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

81 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

k6

Inherit methods from multiple trait to any class

License License NPM downloads Version Build

Trait.js is a helper which allows javascript to have the same behavior with the Php Trait feature. Allows you to inherit or reuse methods to any classes or objects. There's been other libraries/repositories out there that is also respresents the javascript equivalent of Php - Traits. Among them, this solution is a simple and lightweight package and serves only one purpose, allow any classes to inherit methods from multiple traits.

Installation

NPM
npm install trait.js --save

CDN

https://unpkg.com/trait.js@1.2.12/build/trait.min.js

Sample Usage:

Let's create a simple trait that displays the user's fullname.

UserTrait.js

import trait from 'trait.js';

export default trait({
  getFullname() {
    return `${this.firstName} ${this.lastName}`;
  },
});

User.js

For example we have a user model that wants to use the UserTrait.js

import UserTrait from './UserTrait.js';

export default class User {
  constructor({ firstName, lastName }) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

UserTrait.inheritTo(User);
// or
UserTrait.in(User); // a shorthand for inheritTo

Let's try to use that method:

import User from './User.js';

const user = new User({
  first_name: 'Foo',
  last_name: 'Bar',
});

// We can now use the trait method getFullname()
console.log(user.getFullname()); // Foo Bar

Why use Trait?

Javascript only supports single inheritance: a child class can inherit only from one single parent.

So, what if a class needs to inherit multiple behaviors? OOP traits solve this problem.

Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected).

License

MIT © 2020 Regs Isabelo

FOSSA Status

About

🔥 A Php Trait Javascript Equivalent helps you reuse methods in single inheritance languages such as PHP & Javascript.

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published