symbol-class
v1.0.0
Published
A class system for when you can use Symbol(), but not the ES6 class.
Downloads
2
Maintainers
Readme
symbol-class
A fork of strict-class, which uses Symbol()
for private properties instead of __underscores
. This acts as a transitional class system between ES5 and ES6, since Symbol()
is more widely supported than class
(as of the creation of this package).
Usage
var Class = require('symbol-class');
var Person = Class.extend({
constructor: function(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
},
greet: function() {
console.log('My name is ' + this.name + '.');
},
get name() {
return this.firstName + ' ' + this.lastName;
},
set name(val) {
var parts = val.split(' ');
this.firstName = parts[0];
this.lastName = parts.slice(1).join(' ');
}
});
var john = new Person('John', 'Smith');
john.greet(); // => "My name is John Smith."
john.name = "John Brown";
john.greet(); // => "My name is John Brown."
Extending a Class
var Pirate = Person.extend({
greet: function greet() {
greet.__super.call(this);
console.log("Arrrrrrr, matey!");
}
});
var blackbeard = new Pirate('Captain', 'Blackbeard');
blackbeard.greet(); // => "My name is Captain Blackbeard. Arrrrrrr, matey!"
blackbeard.name = "Ghost of Blackbeard";
console.log(blackbeard.firstName); // => "Ghost";
Mixins
Person.addMethods({
isGhost: function() {
return /\bghost\b/i.test(this.name);
}
});
john.isGhost() // => false
blackbeard.isGhost() // => true
Implementation Details
###Only functions###
Unlike in strict-class, when using .extend(object)
or .addMethods(object)
, only methods, getters, and setters will be recognized in the object
argument. Other properties will be ignored.
###No funny business###
Only the object
's own properties are recognized, not inherited ones.