简体   繁体   中英

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!?

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

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!

I don't understand very much what you are attempting to do, but you can clone Object.prototype like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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