Skip to content Skip to sidebar Skip to footer

Javascript: How Can I Mix In Methods Of Another Object B To My Object A Without Copying But With Linking?

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(

Solution 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.

Solution 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 = newObject(my); // create an object of the prototype my;

o1.f(); // haa;

my.f = function() { return"hoooo" };

o1.f() // hoooo

Post a Comment for "Javascript: How Can I Mix In Methods Of Another Object B To My Object A Without Copying But With Linking?"