2012-12-21 17 views
8

Questa è una domanda di follow-up dalla mia ultima domanda.prototipo JavaScript 'questo' numero

Simple javascript prototype issue

io sono un po 'nuova utilizzando JavaScript prototype così dispiaciuto per il secondo posto.

Desidero assegnare l'elemento selezionato id all'array this.name.

task.prototype.init=function(){ 
     this.name=[]; //this.name array has to be defined here 

     for (var i; i<5; i++){ 
      var Link=document.createElement('a'); 
       Link.innerHTML='click'; 
       Link.id=value[i]; //I want to assign the value to the this.name array 
       Link.href='#' 
       Link.onclick=this.changeName; 
       document.body.appendChild(Link); 
     } 
} 
task.prototype.changeName=function(){ 

    //How do I push the this.id to the property this.name? 

    //the code below won't work because this refer to the <a> element. 
    this.name.push(this.id);  

    return false; 
    } 

Eventuali suggerimenti per l'attività?

+2

Non utilizzare CapitalCase per le variabili regolari. – katspaugh

+0

Possibile duplicato di [JavaScript Callback Scope] (http://stackoverflow.com/questions/183214/javascript-callback-scope) e [addEventListener e lo scopo di questo] (http://stackoverflow.com/questions/1803195/ addeventlistener-and-the-scope-of-this) e molti altri. – katspaugh

+1

Penso 'nome' è in realtà riservato come well.'callee: function() { argomenti: nullo chiamante: nullo Lunghezza: 0 nome: "" ' – Joe

risposta

15

Il prototipo è a posto, il problema è che this sui gestori di eventi è sempre l'elemento che ha causato l'attivazione dell'evento. In JavaScript, the value of this inside a function depends on how the function is called.

Se si desidera this ad essere vincolati ad un certo valore, è possibile creare una funzione legato con Function.prototype.bind:

var newChangeName = this.changeName.bind(this); 
Link.onclick = newChangeName; 

Nota tuttavia che bind è IE9 + solo. Una soluzione sarebbe:

var that = this; 
Link.onclick = function() { 
    that.changeName(); 
}; 

(Stile nota: userei link invece di Link, la convenzione in js è quello di lasciare le iniziali maiuscole ai costruttori).

1

Usa bind per impostare il this desiderato per il changeName callback:

Link.onclick=this.changeName.bind(this); 
Problemi correlati