1

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?

Dagg Nabbit
77k19 gold badges115 silver badges142 bronze badges
asked May 20, 2012 at 0:26

1 Answer 1

4

The proper way would be to create a DOM element and attach the event handler with JavaScript:

Tester.prototype.show = function() {
 var a = document.createElement('a'),
 self = this; // assign this to a variable we can access in the 
 // event handler
 a.href = '#';
 a.innerHTML = 'test';
 a.onclick = function() { 
 self.test();
 return false; // to prevent the browser following the link
 };
 this.elem.appendChild(a);
};

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, this does not refer to your instance, but to the element the handler is bound to (in this case a). MDN has a good description of this.

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 this behaves in event handlers.

It's also certainly helpful to make yourself familiar with the DOM interface.

answered May 20, 2012 at 0:32
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.