xcstream
V2EX  ›  问与答

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

  •  
  •   xcstream · Mar 26, 2020 · 2111 views
    This topic created in 2272 days ago, the information mentioned may be changed or developed.
    比如

    A.add100(1) == 101


    A.add200(1) == 201


    ...
    3 replies    2020-03-26 01:37:36 +08:00
    FeifeiJin
        1
    FeifeiJin  
       Mar 26, 2020 via Android
    eval 理论上可以的
    xcstream
        2
    xcstream  
    OP
       Mar 26, 2020   ❤️ 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  
       Mar 26, 2020
    基本就是 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))
    ```
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5184 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 05:45 · PVG 13:45 · LAX 22:45 · JFK 01:45
    ♥ Do have faith in what you're doing.