Reputation: 4293
I am writing a class which manipulates some innerHTML & onclick tags of a div, which puts some function in it that is calls something within the class, however, as there are going to be more than one use of the class on a single page.
I was wondering if it was possible within the class to workout what that particular object had been labelled?
function Bob() {
this.test = function()
{
alert('test');
}
this.Bob = function()
{
element.onClick = function() {(some piece of code).test();};
element.innerHTML = "<a href=\"" + (some piece of code) + ".test();\">Test</a>";
}
}
Upvotes: 0
Views: 74
Reputation: 169373
function Bob() {}
Bob.prototype.test = function () {
/* do things */
};
Bob.prototype.Bob = function () {
element.addEventListener("click", function () {
this.test();
}.bind(this));
toArray(element.childNodes).forEach(function (node) {
element.removeChild(node);
});
var button = document.create("button");
button.classList.add("button-style");
element.appendChild(button);
button.addEventListener("click", function () {
this.test();
}.bind(this));
};
You want to use .bind
to bind functions to a `thisContext
Upvotes: 2
Reputation: 6955
function Bob() {
var self = this;
this.test = function()
{
alert('This is the Bob class');
}
element.onClick = function() {
self.test();
};
}
Due to how closures work the "self" variable will still be inscope within that element's onclick even after the Bob constructor returns.
Simply have different classes return different alert messages inside the test function
Upvotes: 1