问题
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?
回答1:
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.
回答2:
either, you call assign again. or you can do something like this: (there are no pointers in javascript, however: objects are always passed by reference (in contrast to normal values like numbers, strings,.. which are passed by value).
Hence:
var my = {
f: function() { return "haa" }
}
var o1 = {};
Object.assign(o1, {my: my}); // this is the crucial point, you are assigning a reference to my
o1.my.f() // "haa";
my.f = function() { return "hoooo" };
o1.my.f() // "hoooo";
After some research, I found something much simpler:
var my = {
f: function() { return "haa" }
}
var o1 = new Object(my); // create an object of the prototype my;
o1.f(); // haa;
my.f = function() { return "hoooo" };
o1.f() // hoooo
来源:https://stackoverflow.com/questions/36073848/javascript-how-can-i-mix-in-methods-of-another-object-b-to-my-object-a-without