Can a method find out the "this" of its parent object?
Let's say I've come up with a particular sort function that I want to put in the prototype of some Array ba开发者_运维问答sed object (I'll use Array itself here). I can do
Array.prototype.specialSort = function...
but what I'd really like to do is
Array.prototype.sort.special = function...
the problem, of course, is that when it's called, the latter won't know about the Array object, it will only know about the sort, so it can't sort. Is there any magical incantation to pass a "this" down the tree?
Secondary question (since the answer to the primary question is likely "no"): What would you do to implement the notion of "sub-methods" with maximum elegance?
This should be fairly close to what you want:
Array.prototype.sort = function () {
return {
self: this;
, special: function () {
return sortLogic (self);
}
};
};
var xs = [1, 2, 3];
xs.sort ().special ();
Another option would be to use Function.prototype.call
or Function.prototype.apply
, especially if you want arr.sort ()
to sort the list as normal.
Array.prototype.sort.special.call (arr, arg1, arg2, etc);
Using the second method over the first allows one to use the call
and apply
methods easily on the sort.special
method. Could be useful when doing something like the following:
function () {
Array.prototype.sort.special.call (arguments);
}
If you want both worlds, something like this could work:
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);
Thanks for the guidance to both Pointy and trinithis. I think I am clear on the subject now. The sticking point is that, although sort() is a method of the Array, if it's not invoked, it's just a member (or property), so it has no "this". I was wanting the "this" it would have had if it had been invoked. And since I was invoking something at the end of the chain, I was kind of hoping there was some magic that would keep it all method-y. But no.
What I would probably do is have a separate "sorts" method to act as the grouper for my special methods, and leave the existing sort alone.
精彩评论