var foo = {}
class bar {
fiddle() {
alert('boo');
}
}
Object.assign(foo, new bar());
foo.fiddle();
Why doesn't this work? I see foo.fiddle is not a function
.
In my real-world situation, I know that fiddle
exists and I just want to copy it into an existing instance of a different class. Something like
otherInstance['fiddle'] = bar['fiddle']
...but I'm aware that this syntax won't work.
I also find it strange that this guy's example demonstrates Object.assign
copying a function via:
let x = {a: y => y * 2}
let z = Object.assign({}, x)
console.log(z.a(5)); // 10
Clarified:
let calculator = {double: y => y * 2}
let clone = Object.assign({}, calculator)
alert(clone.double(5)); // 10
Modified:
let calculator = {double: y => y * 2}
let clone = {}
Object.assign(clone, calculator)
alert(clone.double(5)); // 10
But my initial example using a class instance doesn't work, presumably due to the way that prototype is mysteriously related.
UPDATE
For now, I've decided to convert a bunch of classes into objects so this isn't as much of a nightmare:
class foo {
foodle() {
console.log('1')
}
}
const bar = {
fiddle: () => {
console.log('2');
}
}
var test = new foo();
var test2 = Object.create(bar);
Object.assign(test, bar);
test.foodle(); // 1
test.fiddle(); // 2
My inner purist would enjoy using classes for all of my components so if there's a solution that allows me to revert the downgrade to objects, I'm all ears!
UPDATE 2
I'm a dummy, this approach actually does work:
var foo = {}
class bar {
fiddle() {
alert('boo');
}
}
var barInstance = new bar();
foo['fiddle'] = barInstance['fiddle'];
foo.fiddle(); // boo