Last active
October 21, 2015 16:10
-
-
Save iwege/d77cca95bb1d8c8a41f9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function _overload(all, target, name, descriptor) { | |
if (!target.__$$methods) { | |
target.__$$methods = {}; | |
target.__$$methods[name] = []; | |
target.__$$methods[name].push({len: descriptor.value.length, fn: descriptor.value, all: all}); | |
} else { | |
target.__$$methods[name].push({len: descriptor.value.length, fn: descriptor.value, all: all}); | |
} | |
descriptor.value = function () { | |
let length = arguments.length; | |
let fn = this.__$$methods[name].filter((item)=>(item.len == length || item.all)).pop(); | |
if (!fn) { | |
throw new Error('no fn defined'); | |
} | |
this::fn.fn(...arguments); | |
} | |
} | |
function overload(all) { | |
if (arguments.length == 3) { | |
return _overload(false, ...arguments); | |
} | |
return _overload.bind(null, all); | |
} | |
////////////////// overload 测试 | |
class Base { | |
constructor() { | |
} | |
@overload(true) | |
fn() { | |
console.log('print all', arguments); | |
} | |
@overload | |
fn(a, b, c) { | |
console.log('from 3', a, b, c); | |
} | |
fn2() { | |
console.log('fn2, print from base'); | |
} | |
} | |
class ClassA extends Base { | |
@overload | |
fn(a) { | |
console.log(a); | |
} | |
fn2() { | |
console.log(super.fn2); | |
super.fn2(); | |
console.log('fn2 from Class A'); | |
} | |
} | |
var test = new ClassA(); | |
test.fn(1); | |
test.fn(); | |
test.fn(1, 2, 3); | |
test.fn(1, 2, 3, 4); | |
test.fn2(); | |
//////////////////////// overload class的测试 | |
function overloadClass(target) { | |
console.log(target.name); | |
console.log(target.length); | |
console.dir(Object.getOwnPropertyNames(target.prototype)); | |
console.dir(target.prototype); | |
} | |
@overloadClass | |
class Base2 { | |
constructor() { | |
} | |
fn() { | |
} | |
} | |
@overloadClass | |
class ClassB extends Base2 { | |
constructor(b) { | |
super(); | |
} | |
fn() { | |
} | |
fn2() { | |
} | |
fn(b) { | |
console.log('test'); | |
} | |
fn(a, b, c) { | |
console.log('test3'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment