V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
xcstream
V2EX  ›  问与答

js 能动态创建不存在的方法么

  •  
  •   xcstream · 2020-03-26 01:05:49 +08:00 · 1423 次点击
    这是一个创建于 1464 天前的主题,其中的信息可能已经有所发展或是发生改变。
    比如

    A.add100(1) == 101


    A.add200(1) == 201


    ...
    3 条回复    2020-03-26 01:37:36 +08:00
    FeifeiJin
        1
    FeifeiJin  
       2020-03-26 01:06:22 +08:00 via Android
    eval 理论上可以的
    xcstream
        2
    xcstream  
    OP
       2020-03-26 01:16:35 +08:00   ❤️ 1
    百度了一下 解决了

    const { MethodMissingClass } = require('unmiss')
    class Add extends MethodMissingClass {
    methodMissing(name, ...args) {
    return Number(name.substr(3)) + args[0]
    }
    }
    const A = new Add;
    const r = A.add1000(1)
    console.log(r)
    seki
        3
    seki  
       2020-03-26 01:37:36 +08:00
    基本就是 proxy 的玩法

    ```
    import _ from 'lodash'

    const wrapped = {}

    const proxy = new Proxy(wrapped, {
    get(target, p, val) {
    if (_.isString(p) && _.startsWith(p, 'add')) {
    const v = parseInt(p.replace('add', ''), 10)
    return q => q + v
    }
    }
    })

    console.log(proxy.add100(1))
    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5270 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 09:22 · PVG 17:22 · LAX 02:22 · JFK 05:22
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.