Can a method know the "this" of its parent?

Let's say I came up with a specific sorting function that I want to put in a prototype of some object based on an array (I myself will use Array here). I can do

Array.prototype.specialSort = function...

but I really would like to do it

Array.prototype.sort.special = function...

the problem, of course, is that when it is called, the latter will not know about the Array object, it will only know about sorting, so it cannot be sorted. Is there a magic spell to pass "this" across a tree?

Secondary question (since the answer to the main question is most likely “no”): what would you do to implement the concept of “sub-methods” with maximum elegance?

+3
source share
2 answers

, :

Array.prototype.sort = function () {
  return {
      self: this;
    , special: function () {
        return sortLogic (self);
      }
  };
};

var xs = [1, 2, 3];
xs.sort ().special ();

- Function.prototype.call Function.prototype.apply, , arr.sort () .

Array.prototype.sort.special.call (arr, arg1, arg2, etc);

call apply sort.special. :

function () {
  Array.prototype.sort.special.call (arguments);
}

, - :

Array.prototype.sort = (function () {
  var special = function () {
    if (this [0] > this [1]) {
      var tmp = this [0];
      this [0] = this [1];
      this [1] = tmp;
    }
    return this;
  };
  var sort = function () {
    var context = this;
    return {
      special: function () {
        return special.apply (context, arguments)
      }
    };
  };
  sort.special = special;
  return sort;
}) ();


/*** Example Below ***/


function foo () {
  Array.prototype.sort.special.call (arguments);
  var xs = [5, 2, 3];
  xs.sort ().special ();
  alert (arguments);
  alert (xs);
}

foo (9, 6);
+1

Pointy trinithis. , . , , sort() , , ( ), "this". "this", . - , , - , . .

, , , , "", .

0

Source: https://habr.com/ru/post/1755873/


All Articles