2010-09-08 15 views
5

Como alguien que está intentando tomar un enfoque más orientado a objetos a mi programación javascript, he topado con un obstáculo que estoy seguro es algo muy básico, pero, tome la siguiente implementación de objetos (suponga que el objeto jQuery está disponible para el código):JavaScript Scope question

function Foo() 
{ 
    this.someProperty = 5; 
} 

Foo.prototype.myFunc = function() 
{ 
    //do stuff... 
}; 

Foo.prototype.bar = function() 
{ 
    //here 'this' refers to the object Foo 
    console.log(this.someProperty); 

    $('.some_elements').each(function() 
    { 
     //but here, 'this' refers to the current DOM element of the list of elements 
     //selected by the jQuery selector that jquery's each() function is iterating through 
     console.log(this); 

     //so, how can i access the Foo object's properties from here so i can do 
     //something like this? 
     this.myFunc(); 
    }); 
}; 

Respuesta

6

puede utilizar temporalmente otra variable para que apunte a la correcta este:

Foo.prototype.bar = function() 
{ 
    //here 'this' refers to the object Foo 
    console.log(this.someProperty); 

    var self = this; 

    $('.some_elements').each(function() 
    { 
     self.myFunc(); 
    }); 
}; 
+0

Sabía que sería algo así de simple, gracias :-) –

5

Antes de entrar al function se pasa a each, que necesita para capturar this de la función externa en una variable y luego usar la variable dentro del function que pasar al each.

function Foo() 
{ 
    this.someProperty = 5; 
} 

Foo.prototype.myFunc = function() 
{ 
    //do stuff... 
}; 

Foo.prototype.bar = function() 
{ 
    // in here, this refers to object Foo 

    // capture this in a variable 
    var that = this; 

    $('.some_elements').each(function() 
    { 
     // in here, this refers to an item in the jQuery object 
     // for the current iteration 

     console.log(that); 
     that.myFunc(); 
    }); 
}; 

Como has encontrado a cabo, this dentro de la función que se pasa a each se refiere al elemento actual en el objeto jQuery en cada iteración es decir, primera iteración se refiere al tema en 0, segunda iteración se refiere a tema en la propiedad 1, etc.

0

estás descubriendo la USEF ulles de JavaScript closures. Son increíblemente poderosos y útiles para hacer un código conciso. Esta es una de las funciones de JavaScript más útiles que puede intentar comprender.