1

Im working on a js game, and trying to clone an object, but I keep having this error :

this[i].clone is not a function

this is my code :

Object.prototype.clone = function() {
    var i, newObj = (this instanceof Array) ? [] : {};
    for (i in this) {
        if (i === 'clone') {
            continue;
        }
        if (this[i] && typeof this[i] === "object") {
            newObj[i] = this[i].clone();
        } else {
            newObj[i] = this[i];
        }
    }
    return newObj;
};

I tried to remplace 'clone' with this solution :

JSON.parse(JSON.stringify(object)) it didn't work. any help please ?

Amine
  • 31
  • 3
  • Does this answer your question? [How do I correctly clone a JavaScript object?](https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object) – romellem Sep 30 '21 at 13:57
  • 1
    Can you provide a example of how you're using this code as a [mcve] and add it to the question? – Andy Sep 30 '21 at 13:57
  • `Object.prototype.clone =` Just a heads up, modifying built in prototypes is not a great idea, unless polyfilling. – Keith Sep 30 '21 at 14:19
  • What is the problem with `JSON.parse(JSON.stringify(object))`? – Michał Kolenda Sep 30 '21 at 19:32

1 Answers1

0

It looks as it works

Object.prototype.clone = function() {
    var i, newObj = (this instanceof Array) ? [] : {};
    for (i in this) {
        if (i === 'clone') {
            continue;
        }
        if (this[i] && typeof this[i] === "object") {
            newObj[i] = this[i].clone();
        } else {
            newObj[i] = this[i];
        }
    }
    return newObj;
};

var person = {
    name: 'John',
    address: {
        city: 'New York'
    }
};

var clonedPerson = person.clone();

person.address.city = 'Buenos Aires';

console.log(person.address.city);
console.log(clonedPerson.address.city);

What is your call look like?

Michał Kolenda
  • 163
  • 1
  • 11
  • Thank you for your response ! this is me error message : `[Vue warn]: Error in getter for watcher "clone": "TypeError: this[i].clone is not a function" ` – Amine Sep 30 '21 at 14:12
  • Please paste the code that calls the clone with the error. You can also try to add some `console.log(this[i]);` before `newObj[i] = this[i].clone();` line to figure out which property makes the problem. – Michał Kolenda Sep 30 '21 at 19:23