Peter Seliger
1 min readNov 18, 2024

--

Although the object-based mixin approach might be the most widely used, the examples chosen by the OP already highlight its limitations. This technique can only handle publicly accessible data from the object it is mixed into. Unfortunately, the OP's example does not even illustrate this point. Instead, the OP presents examples involving logging and authentication. Logging, in particular, would rarely, if ever, be implemented as a mixin since it offers no advantage over a straightforward logging function. Similarly, the use of authentication as a mixin is also highly questionable.

A much simpler and more relevant example would have been truly reusable functionality that can be mixed into various data types, such as a first and last implementation for retrieving the first/last character of a string or the first/last item of an array. This would better demonstrate the value and practicality of the mixin approach.

// re-usable mixin implementation.
function first() {
return this.at(0);
}
function last() {
return this.at(-1);
}
const withFirstLastSlot = {
first,
last,
};

// mixin in at prototype level.
// Object.assign(Array.prototype, withFirstLastSlot);
Object.assign(String.prototype, withFirstLastSlot);

// mixin in directly at instance level.
const arr = Object.assign(['foo', 'bar', 'baz'], withFirstLastSlot);


console.log('foo, bar, baz'.first()); // 'f'
console.log('foo, bar, baz'.last()); // 'z'

// every string value/instance features it due to prototypal delegation.
console.log(''.last); // 'last() { return this.at(-1); }'


console.log(arr.first()); // 'foo'
console.log(arr.last()); // 'baz'

// no prototypal delegation; mixin only got applied to a specific array.
console.log([].first); // undefined

--

--

Responses (1)