I have following code, written in ES6 plus some Stage 3 proposals:
class Parent {
constructor(x){
this.x = x;
this.otherProperty = "preserve across copy";
}
printX=()=>{
console.log(this.x);
}
squareX=()=>{
this.x = this.x *this.x;
}
}
class Child extends Parent {
constructor(x){
super(x);
}
}
const c = new Child(20);
const copy = {...c, x: 10};
console.log(JSON.stringify(c));
c.squareX();
console.log(JSON.stringify(c));
console.log(JSON.stringify(copy));
copy.squareX();
console.log(JSON.stringify(copy));
Live demo: https://jsbin.com/wuqenabaya/1/edit?js,console
The idea is to create a copy of the instance c
while updating some of it's properties. The output of this code is:
{x: 20, otherProperty: "preserve across copy"}
{x: 400, otherProperty: "preserve across copy"}
{x: 10, otherProperty: "preserve across copy"}
{x: 10, otherProperty: "preserve across copy"}
So as you can see the copy.squareX()
does not update the instance copy
. The issue is that the function squareX()
is still bound to the old instance c
.
What I want is to have the last call to squareX()
to update the instance copy
. How can this be achieved?
EDIT: I'm using Babel with following plugins, to allow the use of the new JS features (spread, function props).
{
"presets": [
["es2015", { "modules": false }],
"stage-0",
"react"
],
"plugins": [
"react-hot-loader/babel",
"transform-object-rest-spread",
"transform-class-properties",
"transform-flow-strip-types"
]
}