I have the following javascript code found also in this fiddle: http://jsfiddle.net/periklis/k4u4c/
<button id = "element_id" class = "myclass">Click me</button>
<script>
$(document).ready(function() {
this.myfunc = function() {
console.log('Hello world');
}
this.myfunc();
$('#element_id').select('.myclass').bind('click', function() {
this.myfunc(); //Obviously this doesn't work
});
});
</script>
How can I call this.myfunc() when the element is clicked? I don’t want to define the myfunc() in the global space.
Thanks as always
Create a local variable that references to the function, that way it is accessible from the anonymous function and you don’t end up with
myfuncin the global namespace.If you, on the other hand, assign
var that = this;, then your methodmyfuncwill be stored on the HTMLDocument object (from$(document)), which is perhaps not what you want. But if that’s what you want, then you do this (as others have suggested also, I might add).// Simon A