How to clone a prototype with property methods?

时光总嘲笑我的痴心妄想 提交于 2019-12-12 01:46:29

问题


I am using the Typed.React library which includes a method to extend one prototype definition with that of another:

function extractPrototype(clazz) {
    var proto = {};
    for (var key in clazz.prototype) {
        proto[key] = clazz.prototype[key];
    }
    return proto;
}

If the provided class defines property methods, this function has a side effect of executing the get method e.g.

var TestObject = (function () {
    function TestObject() {
        this.str = "test string";
    }
    Object.defineProperty(TestObject.prototype, "TestProperty", {
        get: function () {
            console.log("exec get");
            return this.str;
        },
        set: function (value) {
            console.log("exec set");
            this.str = value;
        },
        enumerable: true,
        configurable: true
    });
    return TestObject;
})();

var extracted = extractPrototype(TestObject);

When extactPrototype accesses TestObject.prototype["TestProperty"], it will execute the property get method and print:

exec get

How would I duplicate a prototype with property methods without executing them?


回答1:


I think you are looking for the new ES6 Object.assign function.

Of course there's a simpler fix to your problem - just don't access and set properties, copy their property descriptors:

function extractPrototype(clazz) {
    var proto = {};
    for (var key in clazz.prototype) {
        Object.defineProperty(proto, key, Object.getOwnPropertyDescriptor(clazz.prototype, key));
    }
    return proto;
}


来源:https://stackoverflow.com/questions/29298746/how-to-clone-a-prototype-with-property-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!