如何使用属性方法克隆原型? [英] How to clone a prototype with property methods?

查看:68
本文介绍了如何使用属性方法克隆原型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Typed.React库,该库包括一种将一个原型定义扩展为另一个原型定义的方法:

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;
}

如果提供的类定义了属性方法,则此函数具有执行副作用get方法,例如

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);

当extactPrototype访问TestObject.prototype [ TestProperty]时,它将执行属性get方法并打印:

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?

推荐答案

我认为您正在寻找新的ES6 Object。分配 函数。

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;
}

这篇关于如何使用属性方法克隆原型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆