简体   繁体   English

创建双对象又称继承克隆

[英]Create twin object a.k.a. inheritance clone

The working twin(source) function below generates a new object with the same own properties as source and with the same parents (prototype chain). 下面的工作twin(source)函数生成一个新对象,它具有与source相同属性和相同的父对象(原型链)。 (eg twin(isFinite) would be [object Object] and instanceof Function ) Does any native function provide the same effect? (例如twin(isFinite)将是[object Object]instanceof Function )任何本机函数是否提供相同的效果?

/**
 * @param {Object|Function} source
 * @param {(Object|Function|null)=} parent defaults to source's parents
 * @return {Object}
 */
function twin(source, parent) {
    var twin, owned, i = arguments.length;
    source = i ? source : this; // use self if called w/o args
    parent = 2 == i ? parent : Object.getPrototypeOf(source);
    twin = Object.create(parent);
    owned = Object.getOwnPropertyNames(source);
    for (i = owned.length; i--;) {
        twin[owned[i]] = source[owned[i]];
    }
    return twin;
}

Update: A .twin method is available in blood . 更新: 血液中.twin方法。

You can try something like this: 你可以尝试这样的事情:

obj= eval(uneval(objSource));

It only works in FF but the idea is to serialize an object and the eval the serialized string instantiating (prototyping) a new object with the same properties as the first one. 它仅适用于FF,但其目的是序列化一个对象和eval,序列化的字符串实例化(原型化)一个具有与第一个相同属性的新对象。

You can use also the function JSON.stringify as the "uneval" function. 您还可以使用函数JSON.stringify作为“uneval”函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM