I do not understand a piece of code from the article about impurities (mixin), where the circuit is “mixed in”. Specifically, in lines 1 and 2, it is not clear what is happening? Link to the article https://habr.com/post/132340/

function extend_2(object) { var mixins = Array.prototype.slice.call(arguments, 1); for (var i = 0; i < mixins.length; ++i) { for (var prop in mixins[i]) { if (typeof object.prototype[prop] === "undefined") { bindMethod = function (mixin, prop) //(1) { return function () { mixin[prop].apply(this, arguments) } } object.prototype[prop] = bindMethod(mixins[i], prop);//(2) } } } } 

  • Honestly, in these lines crap happens. One of two things: either it was an example of how not to do it - or the author of the article himself does not know what he is doing. - Pavel Mayorov
  • Specifically, in lines 1 and 2 , the function is declared in the first line, and executed in the second. It is worth adding a link to the article. - Grundy
  • habr.com/post/132340 - ZdraviSmisl
  • @ZdraviSmisl, 11 years old, quite a lot of time has passed - Grundy
  • Well, on js lorny, unfortunately comments on the lessons, having the maximum number of grades give references to articles of 5 years old (and more) ago - ZdraviSmisl

1 answer 1

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:

  1. creates a function that

    1. takes two parameters
    2. returns a new function
    3. in the returned function, the method is called, which is set to the current this and arguments .
  2. 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();