简体   繁体   English

我如何创建一个Object.prototype克隆

[英]how do i create an Object.prototype clone

I have an incomplete clone of Object.prototype , made to the best of my knowledge, can you show me how to finish it!? 我有一个不完整的Object.prototype克隆, Object.prototype我所知,您能告诉我如何完成它吗?

The Code 编码

function duplicate_object_prototype(){
    var aRef=[
        '__defineGetter__',
        '__defineSetter__',
        '__lookupGetter__',
        '__lookupSetter__',
        'constructor',
        'hasOwnProperty',
        'isPrototypeOf',
        'propertyIsEnumerable',
        'toLocaleString',
        'toString',
        'valueOf',
        '__proto__'
    ];

    var clone = Object.create(null);

    for(var i in aRef){
        var ref = aRef[i];
        var pro = Object.prototype[ref];
        clone[ref] = pro;
        Object.defineProperty(clone,ref,{
            writable:false,
            enumerable:false,
            configurable:false
        });
    };

    console.log('clone:',clone);

    return clone;
}

The Concept 这个概念

Create the clone, then: 创建克隆,然后:

Object.defineProperty(Object.prototype,'str',{get:function(){
    return JSON.stringify(this);
}})

Because, through inheritance, Array.prototype now has the str property, configure Array 's prototype chain to point to the clone when it should point to Object.prototype 因为通过继承, Array.prototype现在具有str属性,所以将Array的原型链配置为在应指向Object.prototype时指向克隆。

Object.setPrototypeOf(Array.prototype, clone);

The Logic 逻辑

Now Array points to the clone, no modifications to Object.prototype will be inherited by any Array instance! 现在, Array指向克隆,任何Array实例都不会继承对Object.prototype修改!

I don't understand very much what you are attempting to do, but you can clone Object.prototype like this: 我不太了解您要做什么,但是您可以像这样克隆Object.prototype

var proto = Object.prototype,
    clone = Object.create(null),
    props = Object.getOwnPropertyNames(proto);
for(var i=0; i<props.length; ++i)
    Object.defineProperty(clone, props[i],
        Object.getOwnPropertyDescriptor(proto, props[i])
    );
Object.freeze(clone);

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

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