0

I am using the following technique to differentiate between copy-sourcing two different objects. The o2.copy does the deep copy while o3.copy does the shallow copy.

var o1 = {name: "old"};
console.log(o1);
var o3 = {}; var o2 = {};
o2.copy = function(o){  
    for (var key in o) {        
        o2[key] = ".."+o[key];         
    }
};

o2.copy(o1);
console.log(o2);
o3.copy = function(o){    
    o3 = o;
};
o3.copy(o1);    
console.log(o3);
o2.copy(o1);
o1.name = "New";
console.log(o2);

This works fine.

{ name: 'old' }
{ copy: [Function], name: '..old' }
{ name: 'New' }
{ copy: [Function], name: '..old' }

Now I have an array A.

 var A = [];

Now I want to bind the deep copy to the push of this array A.

Can I override the push this in such a way that if incoming arg is object, it does a deep copy else the default push? Is it possible to do this somehow?

var A = [];

A.push = function (o) {
    if (typeof o === "object") {
        A[A.length] = {} 
        for (var key in o) {        
            A[A.length-1][key] = o[key];  
        } 
    } else {
        console.log("Non-object push");
        push(); //<--- How to call the default array push here
    }
}

A.push (o1); 
A.push ("Test"); 
o1.name = "new";
console.log(A[A.length-1].name) 

//current output is

{ name: 'old' }
+old
{ name: 'NewAgain' }
old
Non-object push

/temp/file.js:35
        push();
        ^
ReferenceError: push is not defined
    at Array.A.push (/temp/file.js:35:9)
    at Object.<anonymous> (/temp/file.js:40:3)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:418:7)
    at startup (bootstrap_node.js:139:9)

1 Answer 1

1

Use .call method for a function object to get default implementation.

var A = [];

A.push = function (o) {
    if (typeof o === "object") {
        A[A.length] = {} 
        for (var key in o) {        
            A[A.length-1][key] = o[key];  
        } 
    } else {
        console.log("Non-object push");
        Array.prototype.push.call(this, o); //<--- How to call the default array push here
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.