let myObject = {}
class MyClass {
myFunction() {
alert('hello');
}
}
Object.assign(myObject, new MyClass());
myObject.myFunction();
Why is this not functioning? I'm getting an error
myObject.myFunction is not a function
.
In my particular case, I am aware that myFunction
exists and I just want to transfer it into another instance of a different class. Something like
anotherInstance['myFunction'] = MyClass['myFunction']
...but I understand that this syntax won't do the trick.
I also noticed that this individual's example shows Object.assign
copying a function using:
let x = {a: y => y * 2}
let z = Object.assign({}, x)
console.log(z.a(5)); // 10
To clarify:
let calculator = {double: y => y * 2}
let clone = Object.assign({}, calculator)
alert(clone.double(5)); // 10
However, in my original example with a class instance, it doesn't seem to work, presumably due to the mysterious relationship with the prototype.
UPDATE
Currently, I've opted to convert multiple classes into objects to simplify things:
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
While I prefer using classes for all components, if there's a solution that allows me to switch back to using classes, I'm open to suggestions!
UPDATE 2
Upon further reflection, this approach actually does work:
let myObject = {}
class MyClass {
myFunction() {
alert('hello');
}
}
var myClassInstance = new MyClass();
myObject['myFunction'] = myClassInstance['myFunction'];
myObject.myFunction(); // hello