Non sono sicuro di aver corretto il titolo della domanda; Si prega di considerare quanto segue per chiarire ...Estendere l'ereditarietà di `this` a metodi/proprietà di un` oggetto`
(function() {
var foo = {
bar: function() {
// Is it possible to reference 'this' as the
// initializing 'object' aka 'e' and not 'foo' ?
// The easy part, currently because 'this' refers to 'foo',
// is returning 'this' aka 'foo' so that chaining can occur
return this;
},
other: function() {
return this;
}
};
Event.prototype.foo = foo;
}());
// usage
document.onmousemove = function(e) {
e.foo.bar().other();
};
Come potrei fare per avere accesso alle this
entro i metodi/puntelli di foo
ma avendo this
si riferiscono a quella iniziale object
alias e
e non foo
?
Il migliore che io sia venuto in mente è questa
(function() {
var foo = function() {
var _foo = this.foo;
_foo._this = this; //recursive reference that I am VERY worried about
return _foo;
};
foo.bar = function() {
var _this = this._this; //_this refers to initial 'object', 'e'
return this; //return 'foo' aka 'this' for function chaining
};
foo.other = function() {
var _this = this._this;
return this;
};
Event.prototype.foo = foo;
}());
// usage
document.onmousemove = function(e) {
e.foo().bar().other();
};
Quello che ho attualmente funziona, ma sono preoccupato per un paio di cose ...
1. Il riferimento ricorsivo dell'assegnazione di e
a e.foo._this
e
2. La ridondanza dell'assegnazione di e
a , se this
si può accedere come e
invece di foo
renderebbe le 'cose' più performanti, in particolare per quanto riguarda qualcosa come un evento di mousemove.
Inoltre, Im cercando di evitare qualcosa di simile ...
Tutti i suggerimenti sono apprezzati, grazie per il vostro tempo.
Quindi, se ho capito bene, in pratica, vuoi accedere a entrambi, l'oggetto 'pippo' e l'elemento che ha attivato l'evento? – basilikum
@basilikum Sì ... un po '? L'evento 'stesso e l'oggetto' foo'. Mi piace "questo" e "questo.foo". Se ciò ha senso? – Terry