Skip to content

Instantly share code, notes, and snippets.

@teramako
Created January 29, 2013 12:48
Show Gist options
  • Save teramako/4663981 to your computer and use it in GitHub Desktop.
Save teramako/4663981 to your computer and use it in GitHub Desktop.
作ってみたけど、あまり格好良い __super__ じゃなかったorz
var [mixin, extend] = (function() {
var wm = WeakMap();
function mixin(aTarget, ...aSources) {
for (let source of aSources) {
for (let key of Object.getOwnPropertyNames(source)) {
let desc = Object.getOwnPropertyDescriptor(source, key);
Object.defineProperty(aTarget, key, desc);
}
}
return aTarget;
}
function extend (aClass, ...aSources) {
var supers = [];
var proto = aSources.shift();
if (typeof proto === "function") {
if (proto.name)
supers[proto.name] = proto.prototype;
proto = proto.prototype;
}
supers.unshift(proto);
for (let source of aSources) {
let target = Object.create(proto);
if (typeof source === "function") {
if (source.name)
supers[source.name] = source.prototype;
source = source.prototype;
}
supers.unshift(source);
proto = mixin(target, source);
}
wm.set(aClass, Object.freeze(supers));
aClass.prototype = mixin(proto, aClass.prototype);
Object.defineProperty(aClass.prototype, "__super__", { get: function(){ return wm.get(aClass); } });
return aClass.prototype;
}
return [mixin, extend];
}());
// example
function Base(...args){ this.init.apply(this, args); }
mixin(Base.prototype, {
init: function (name) {
this.name = name;
},
getName: function(){
return this.name;
},
});
function Foo(...args){
Base.apply(this, args);
}
extend(Foo, Base, {
setName: function(val) {
this.name = val;
},
getName: function() {
var name = this.__super__.Base.getName.call(this);
return "Foo: " + name;
},
});
// test
var f = new Foo("hogehoge");
console.log(f.getName());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment