0

I'm creating a copy of a JS object in order to perform functions on the copy. However, I'm unable to call the functions in the copied object, I just get an error saying that the functions do not exist in this instance, any ideas?

edit: here is the code

obj.isGridStateSolvable();
let tempobj = jQuery.extend(true, {}, obj);
tempobj.isGridStateSolvable();

Line one is working correctly and the function is accessible however the third line is not.

edit 2: here is a testable example

class Num{
    constructor(numParam){
        this.number = numParam;
    }

    incrementNum(){
        this.number++;
    }
}

var num1 = new Num(5);
num1.incrementNum();

console.log(num1); //Outputs 6 as expected

let num2 = jQuery.extend(true, {}, num1);
num2.incrementNum();    //This function does not exist
Rake146
  • 73
  • 1
  • 7
  • `I'm creating a copy of a JS object in order to perform functions on the copy.` how did you make the copy? `any ideas` if you did the `JSON.stringify` -> `JSON.parse`, then that's your problem. There is no functions in JSON, so the "copy" won't have them after being made into that format. – VLAZ Sep 28 '18 at 17:20
  • Could you add a code-snippet to your question containing the code you're using to copy the object, please? – pete Sep 28 '18 at 17:20
  • I forgot to add the code haha, updated now – Rake146 Sep 28 '18 at 17:23
  • 1
    [I cannot reproduce that.](https://jsbin.com/suyurakere/1/edit?js,console) – VLAZ Sep 28 '18 at 17:30
  • I have added a simple example that conveys my problem – Rake146 Sep 28 '18 at 17:42
  • With the new example - `num2` doesn't have the same prototype as `num1`. – VLAZ Sep 28 '18 at 17:54
  • so would I have to do something like this? var num3 = new Num(9); num3 = num1; which would assign num3 the value of num1 in the same format? – Rake146 Sep 28 '18 at 18:05
  • You [can write your own clone function](https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object) and make sure you also do `Object.getPrototypeOf(source)` then `Object.setPrototypeOf(target, sourcePrototype)`. It's more generic, since you can use it for any kind of object. However, with this example you have, I'd probably add a `clone` method that may just do `return new Num(this.number)` but it might also set other properties. It's probably better as not all things might be copyable via a generic clone function. – VLAZ Sep 28 '18 at 18:14

2 Answers2

0

You can try using JS spread.

let tempobj = { ...obj };

It is a new feature from ES and works very well for JS objects copying.

0

There are several projects on npm which will copy the state of an object in JS into a new destination class/module, meaning the functions will be available.

here is a few

dbones
  • 4,415
  • 3
  • 36
  • 52