Al.G.
Al.G.

Reputation: 4387

Calling function's prototype from another which is called by clicking on html element

I have some functions like these:

function start () {
    document.getElementById('div1').onclick = clicked;
}
function clicked () {
    //here I want to use both the html element and the another_function
    alert('clicked div1: ' + this.innerHTML);
    another_function();
}
function another_function () {
    alert('I am another function.');
}

(in the html code I have only a div with id="div1")

They work obviously fine, but now I want to "collect" them in one object function.
Now I have this:

function Obj () {
    document.getElementById('div2').onclick = this.clicked;
}
Obj.prototype.another_function = function () {
    alert("I am another function!");
}
Obj.prototype.clicked = function () {
    alert('clicked div2: ' + this.innerHTML);
    this.another_function();//doesn't work
    Obj.another_function();//this doesn't work, too
}

How can I call another_function()?
FIDDLE

Upvotes: 0

Views: 44

Answers (2)

adeneo
adeneo

Reputation: 318182

The value of this in the event handler is the element not the object, you can change it to reference the object instead with bind()

function Obj () {
    document.getElementById('div2').onclick = this.clicked.bind(this);
}
Obj.prototype.another_function = function () {
    alert("I am another function!\n" + 
          "I have just been called by the Obj function!");
}
Obj.prototype.clicked = function (e) {
    alert('clicked div2: ' + e.currentTarget.innerHTML);
    this.another_function();
}

FIDDLE

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59232

You can call another_function() like this:

var two = new Obj();
two.another_function();

Upvotes: 0

Related Questions