bamboopanda bamboopanda - 24 days ago 7
jQuery Question

"this" changes value on click

If I have the following code:

function Something() {
this.randomElement = $("#element");
}

Something.prototype = {

functionOne: function() {
console.log("hello");
},

functionTwo: function() {
this.randomElement.click(function(e) {
this.functionOne(); //this becomes pointed at randomElement
});
}
}


How can I write this in a clean way where I wouldn't have to use
Something.prototype.functionOne()
to replace
this.functionOne()
inside of functionTwo? Since the click event changes the value of this?

Answer

Because this is bound to the item that is clicked. You need to use bind

this.randomElement.click( this.functionOne.bind(this) ); 

or jQuery's proxy.

this.randomElement.click( $.proxy(this.functionOne, this) );