Basic Information Hiding

var Account = $Class('Account').body({
  '‌private balance': 0,
  
  '‌protected checkAmount': function(amount) {
    return amount >= 0;
  },
  
  '‌public deposit': function(amount) {
    if (this.checkAmount(amount))
      this.balance += amount;
  },
  
  getBalance: function(amount) {
    return this.balance;
  } // defaults to "public"
});

var myAccount = new Account();
myAccount.deposit(100);
myAccount.getBalance(); // 100
myAccount.balance; // undefined
myAccount.checkAmount; // undefined

Static Members

var Item = $Class('Item').body({
  price: 0,
  '‌static tax': 0.13,
  
  __construct: function(price) {
    this.price = price;
  } // constructor
  
  actualPrice: function() {
    return this.price + this.price * this.tax;
  },
});

var book = new Item(3.50);
var chocolate = new Item(1.23);

book.actualPrice(); // 3.955
chocolate.tax = 0.15;
book.actualPrice(); // 4.025

Inheritance

var User = $Class('User').body({
  name: '',
  '‌protected role': 'user',
  '‌private password': '',
  
  __construct: function(name, password) {
    this.name = name;
    this.password = password;
  },
  
  checkPassword: function(password) {
    return password === this.password;
  }
});

var Admin = $Class('Admin').extends(User).body({
  '‌protected role': 'admin', // overrides User's role
  
  __construct: function(name, password) {
    this.__super.__construct(name, password); // call superclass's constructor
  },
  
  getName: function() {
    return this.name; // inherits name
  },
  
  getRole: function() {
    return this.role;
  },
  
  getPassword: function() {
    return this.password; // can't access superclass's private member
  },
  
  getPassword2: function() {
    return this.__super.password; // still can't access private member
  }
});

var leo = new Admin('Leo', '123');
leo.getName(); // 'Leo'

leo.role; // undefined
leo.getRole(); // 'admin'

leo.password; // undefined
leo.getPassword(); // undefined
leo.getPassword2(); // undefined

leo.checkPassword('123'); // true

Const and Final

var Hasher = $Class('Hasher').body({
  '‌const salt': 'QwErTy',
  
  '‌final hash': function(str) {
    return sha256(str + salt);
  }
});

var PasswordHasher = $Class('HashChecker').extends(Hasher).body({
  hash: function(str) { // $Class error: Cannot override "hash".'
    return md5(str + salt);
  },
  
  setSalt: function(salt) {
    this.salt = salt;
  }
});

var passHash = new PasswordHasher();
passHash.setSalt('123'); // "salt" is read-only
passHash.salt; // QwErTy

Download

Full Source     or     2KB minified

Notes