2013-06-18 5 views
5

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.

jsFiddle Here


Inoltre, Im cercando di evitare qualcosa di simile ...


Tutti i suggerimenti sono apprezzati, grazie per il vostro tempo.

+0

Quindi, se ho capito bene, in pratica, vuoi accedere a entrambi, l'oggetto 'pippo' e l'elemento che ha attivato l'evento? – basilikum

+0

@basilikum Sì ... un po '? L'evento 'stesso e l'oggetto' foo'. Mi piace "questo" e "questo.foo". Se ciò ha senso? – Terry

risposta

2

Con un sottile cambiamento per ciò che avete si può rendere le cose più semplici:

(function() { 
    var foo = function() { 
     this.foo.event = this; 
     return this.foo; 
    }; 
    foo.bar = function() { 
     /// the event can be found in this.event 
     return this; 
    }; 
    foo.other = function() { 
     /// the event can be found in this.event 
     return this; 
    }; 
    Event.prototype.foo = foo; 
}()); 

// usage 
document.onmousedown = function(e) { 
    e.foo().bar().other(); 
}; 

Questo però sta facendo una modifica all'oggetto condiviso foo, si potrebbe desiderare di riscrivere le cose in modo che e.foo() restituisce una nuova istanza di foo invece, e sposta gli altri metodi sul prototipo foo's.

(function() { 
    var foo = function(event) { 
     this.event = event; 
    }; 
    foo.prototype.bar = function() { 
     /// the event can be found in this.event 
     return this; 
    }; 
    foo.prototype.other = function() { 
     /// the event can be found in this.event 
     return this; 
    }; 
    Event.prototype.foo = function() { 
     return new foo(this); 
    }; 
}()); 

In questo modo si sta creando una nuova istanza di foo ogni volta, ma significa che il vostro aggiunta della proprietà event è localizzato a tale istanza; i metodi prototipati saranno condivisi tra tutte le istanze quindi non è male da un punto di vista ottimistico.

+0

molto bello ...^_^ – Terry

+0

@Terry Nessun problema. Ci sono sempre molti modi per approcciare una soluzione in JavaScript, è la ragione per cui mi piace tanto quanto una lingua;) – Pebbl

+0

* I vertici sono vigorosamente d'accordo *. Forse è l'effetto "novità" ancora in piena fioritura, perché sono ancora nuovo di JS, ma non credo. È un linguaggio molto espressivo e adoro impararlo. Grazie per l'aiuto! – Terry

2

Forse che avrebbe funzionato per voi:

utilizzare il metodo apply per cambiare il contesto this nel metodo chiamato e utilizzare this.foo per riferirsi a foo:

(function() { 
    var foo = function() { 
     console.log(this); 
     return this.foo; 
    }; 
    foo.bar = function() { 
     console.log(this); 
     return this.foo; 
    }; 
    foo.other = function() { 
     console.log(this); 
     return this.foo; 
    }; 
    Event.prototype.foo = foo; 
}()); 

// usage 
document.onclick = function (e) { 
    console.log(
     e.foo.apply(e).bar.apply(e).other.apply(e) 
    ); 
}; 

FIDDLE

+0

voto +1. So che i mendicanti non dovrebbero essere scelti, ma speravo di ottenere qualcosa di più inclusivo (se è la parola giusta?) Poi più chiamate 'call' o' apply'. Indipendentemente da ciò, ancora fantastico, grazie basilikum^_^ – Terry

+0

Grazie! :) Bene, la soluzione di pebbl fa esattamente questo. Un modo molto carino per risolvere questo. – basilikum

0

Forse sarebbe più semplice associare la tua funzione al suo oggetto:

someElement.onEvent = myObject.myHandlerFunction.bind(myObject); 

così quando verrà chiamata questa funzione, il suo 'this' sarà myObject.

Quindi è possibile utilizzare e.target per accedere all'elemento.

Problemi correlati