How do I execute a JS object’s function property from an HTML link?
I have the following JS:
function Tester(elem) {
this.elem = document.getElementById(elem);
}
Tester.prototype.show = function() {
this.elem.innerHTML = '<a href="javascript: this.test();">test</a>';
};
Tester.prototype.test = function() {
alert("a");
};
Here is the HTML:
<script type="text/javascript">
var test = new Tester("test");
test.show();
</script>
When I click on the link that gets rendered, it cannot identify the test() function. How would I get it so when a user clicks on the link, the test() function is executed?
The proper way would be to create a DOM element and attach the event handler with JavaScript:
Since the event handler forms a closure, it has access to the variables defined in the outer function (
Tester.prototype.show). Note that inside the event handler,thisdoes not refer to your instance, but to the element the handler is bound to (in this casea). MDN has a good description ofthis.quirksmode.org has some great articles about event handling, the various ways you can bind event handlers, their advantages and disadvantages, differences in browsers and how
thisbehaves in event handlers.It’s also certainly helpful to make yourself familiar with the DOM interface.