In the specified lines
bindMethod = function (mixin, prop) //(1) { return function () { mixin[prop].apply(this, arguments) } } object.prototype[prop] = bindMethod(mixins[i], prop);//(2)
The following happens:
creates a function that
- takes two parameters
- returns a new function
- in the returned function, the method is called, which is set to the current
this and arguments .
the created function is called and the result is written to the variable.
If you do not pay attention that bindMethod into the global scope, you can say that this function is not needed at all, since in addition to creating another function it does nothing.
Therefore, this code can be replaced by the following:
object.prototype[prop] = mixins[i][prop];
If you read the original article, it can be noted that this function was introduced in order to be able to replace the mixin function itself, after it has already been mixed in somewhere.
Example:
function extend_2(construct, ...mixins) { mixins.forEach(mixin => { for (var prop in mixin) { if (typeof construct.prototype[prop] === "undefined") { var bindMethod = function(mixin, prop) //(1) { return function() { mixin[prop].apply(this, arguments) } } construct.prototype[prop] = bindMethod(mixin, prop); //(2) } } }); } var mixins = { say: function() { console.log('base say') } } function A() {} extend_2(A, mixins); var a = new A(); a.say(); mixins.say = function() { console.log('new say') } a.say();