If I create an Object A:
let A = {};
And want to mix in methods from another Object B:
let B = {
foo() {
alert("Boo!");
}
};
Normally I would call:
Object.assign(A, B);
Then I change my function foo:
Object.assign(B, {
foo() {
alert("Hooray!");
}
});
After that I call foo:
A.foo(); // Actual output: "Boo!"
But I want that output to be "Hooray!". So far I found out, that Object.assign only copies methods in the target, but it doesn't link them. About inheritance and composition I found useful blogposts here:Why prototypical inheritance matters and most dominantly here: Understanding Prototypes, Delegation & Composition
I want to mix a method in an Object, but not copy the methods, much more rather I want an assignment to the definition of the mixed in function.
How is this possible?
Prototype inheritance comes to your rescue:
var A = Object.create(B);
A.foo();
B.foo = …;
A.foo(); // something else
Of course, this is not strictly a "mixin" any more, and you can only inherit via the prototype link from one other object only (though you can build an inheritance chain).
If you are looking to mix multiple independent objects into your existing A
object, then that is not possible. Sorry.