从另一个调用函数的原型,通过单击html元素调用

时间:2014-03-30 11:38:30

标签: javascript function object

我有一些这样的功能:

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.');
}

(在html代码中,我只有一个带id="div1"的div)

他们的工作显然很好,但现在我想"收集"它们在一个对象函数中 现在我有了这个:

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
}

如何拨打another_function()
FIDDLE

2 个答案:

答案 0 :(得分:1)

事件处理程序中this的值是元素而不是对象,您可以将其更改为引用对象而不是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

答案 1 :(得分:0)

您可以像这样致电another_function()

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