1. function sum(a, b) {
    2. return a + b;
    3. }
    4. function validatorFunction(func, ...types) {
    5. const proxy = new Proxy(func, {
    6. apply(target, thisArgument, argumentsList) {
    7. types.forEach((t, i) => {
    8. const arg = argumentsList[i]
    9. if (typeof arg !== t) {
    10. throw new TypeError(`第${i+1}个参数${argumentsList[i]}不满足类型${t}`);
    11. }
    12. })
    13. return Reflect.apply(target, thisArgument, argumentsList);
    14. }
    15. })
    16. return proxy;
    17. }
    18. const sumProxy = validatorFunction(sum, "number", "number")
    19. console.log(sumProxy(1, 2))

    不使用Proxy 的方法

    1. function sum(a, b) {
    2. return a + b;
    3. }
    4. function validatorFunction(func, ...types) {
    5. return function(...argumentsList) {
    6. types.forEach((t, i) => {
    7. const arg = argumentsList[i]
    8. if (typeof arg !== t) {
    9. throw new TypeError(`第${i+1}个参数${argumentsList[i]}不满足类型${t}`);
    10. }
    11. })
    12. return func(...argumentsList)
    13. }
    14. return proxy;
    15. }
    16. const sumProxy = validatorFunction(sum, "number", "number")
    17. console.log(sumProxy(1, 2))