MMClass is just another JavaScript Class factory, like Class in Prototype, MooTools or Base2. But it follow the semantics of ES6 max-min class draft, so all codes written with MMClass are expected to be compatible with ES6.
Class Pet {
constructor(name) {
this._name = name
}
speak() {
console.log(this._name + ' says...')
}
}
Class Dog extends Pet {
constructor(name) {
super(name)
}
woof() {
return 'Woof, woof!'
}
speak() {
super.speak()
console.log(this.woof() + " I'm a dog, pet me!")
}
}
Class Cat extends Pet {
meow() {
return 'Meow ~~'
}
speak() {
super.speak()
console.log(this.meow() + " I'm a cat, go away!")
}
}
var Pet = Class({
constructor: function(name) {
this._name = name
},
speak: function() {
console.log(this._name + ' says...')
}
})
var Dog = Class.extend(Pet)({
constructor: function($super, name) {
$super(name)
},
woof: function() {
return 'Woof, woof!'
},
speak: function($super) {
$super.speak()
console.log(this.woof() + " I'm a dog, pet me!")
}
})
var Cat = Class.extend(Pet)({
// if no constructor provided,
// default to constructor(...args) { super(...args) }
meow: function() {
return 'Meow ~~'
},
speak: function($super) {
$super.speak()
console.log(this.meow() + " I'm a cat, go away!")
}
})
var dog = new Dog('Odie')
dog.speak() // Output: Odie says... Woof, woof! I'm a dog, pet me!
var cat = new Cat('Garfield')
cat.speak() // Output: Garfield says... Meow ~~ I'm a cat, go away!
function Pet(name) {
this._name = name
}
Pet.prototype.speak = function() {
console.log(this._name + ' says...')
}
ES6:
class Dog extends Pet {...}
MMClass:
var Dog = Class.extend(Pet)({...})
Note: As ES6, Dog.[[prototype]] should be Pet so that Dog class can inherit all "static" properties on Pet. MMClass follow this semantic via setting __proto__ . Most engines support this pseudo property, if it's not supported, MMClass will copy all properties.
var pet = {
constructor: function(name) {
this._name = name
},
speak: function() {
console.log(this._name + ' says...')
}
}
ES6:
class Dog extends pet {...}
MMClass:
var Dog = Class.extend(pet)({...})
You even can extend null to avoid inheriting the properties from Object.prototype (such as isPrototypeOf/hasOwnProperty/propertyIsEnumerable)
ES6:
class NakedObject extends null {}
MMClass:
var NakedObject = Class.extend(null)()
Note: MMClass requires ES5 environment. You can try es5-shim for legacy browsers (though untested yet).
'use strict'
'import Class from "$PATH_TO/mmclass/src/class.js"'
...
See my.js for more info
Installation:
npm i mmclass
Source:
var Class = require('mmclass').Class
...
define(function(require, exports) {
var Class = require('$PATH_TO/mmclass/dist/mmclass').Class
...
}
<script src="$PATH_TO/mmclass/dist/mmclass"></script>
- Check the recent released ES6 draft to follow the changes (the standard draft is changing dramatically...)