• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

237
Views
Javascript clone() is not a function error

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 ?

almost 3 years ago · Juan Pablo Isaza
1 answers
Answer question

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?

almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error