【问题标题】:Get all functions on JavaScript class ES6 babel [duplicate]获取 JavaScript 类 ES6 babel 上的所有函数 [重复]
【发布时间】:2015-10-27 01:30:48
【问题描述】:

我需要在 Something 类上发现函数 'foo',但它不起作用。这是因为我错过了使用类语法的微妙之处,还是因为 babel 或其他什么?我更愿意尽可能使用“类”,但发现对我来说更重要。

我们那里的天才知道这个吗?

class Something {
    constructor() {
    }
    foo() {
        console.log("foo");

    }

}

var something = {
    foo : function() {
        console.log("foo");
    }
}

var result = Object.getOwnPropertyNames(new Something()).join(", ");
console.log("new Something() = %s", result);

result = Object.getOwnPropertyNames(Something.__proto__).join(", ");
console.log("Something.__proto__ = %s", result);

result = Object.getOwnPropertyNames(something).join(", ");
console.log("var something = %s", result);

产生:

new Something() = 
Something.__proto__ = length, name, arguments, caller, constructor, bind, call, apply, toString
var something = foo

【问题讨论】:

    标签: javascript ecmascript-6 babeljs


    【解决方案1】:

    好的,以上是我想要达到的目标的简化问题:

    module.exports.toDto = (object) =>{
        var result = {};
        Object.getOwnPropertyNames(object.__proto__).map(k => k.match("get(.*)")).filter(m => m).forEach(m => {
            var prop = m[1].toLowerCase();
            var value = object[m[0]]();
            result[prop] = value;
        });
    
        return result;
    };
    

    这使我可以发现类的属性。万岁!

    【讨论】:

    • 这里很棘手。 object.__proto__ 不会列出所有内容。您应该使用 object.prototype 所有实例方法和对象作为静态方法。
    猜你喜欢
    • 1970-01-01
    • 2016-01-08
    • 2016-05-24
    • 2010-12-06
    • 2021-01-09
    • 2018-08-01
    • 2017-06-22
    • 2017-04-28
    相关资源
    最近更新 更多