在面向对象的javascript中使用Onclick

Using Onclick in object oriented javascript

本文关键字:Onclick 面向对象的 javascript      更新时间:2023-09-26

这是我的HTML:的一个片段

 <tr>
                <td class="timeHeader" id="timeInOutString"></td>
                <td id="timeControlHours"></td>
                <td>:</td>
                <td id="timeControlMins"></td>
                <td onclick="this.TimeChangeView.AcceptTime()">Accept</td>
            </tr>
            <tr>
                <td></td>
                <td onclick="this.TimeChangeView.downHours()">

Javascript:

function TimeChangeView(ac) {
    this.downHours = function(){

        //get element by Id
        var value = parseInt(document.getElementById('timeControlHours').innerHTML);
        value = isNaN(value) ? 0 : value;
        value--;
        //add leading zeroes
        value = formatHoursMins(value);
        document.getElementById('timeControlHours').innerHTML = value;
    }


}

错误:

未捕获的类型错误:无法调用未定义的方法"downHours">

我在一个名为TimeChangeView的方法中的脚本中定义了它,但它抱怨我没有定义它,为什么?谢谢

<td onclick="this.TimeChangeView.downHours()">

您正在对象this上调用方法TimeChangeView

this是指函数作为其方法的对象。TimeChangeView而不是对象this的方法,因此它不起作用。(此处thiswindow(

您可以this传递给函数TimeChangeView,如下所示:TimeChangeView(this)

点击此处了解更多信息。

更新

为了让您更好地了解对象在JavaScript中的工作方式,请考虑THIS CODE

正如你所看到的,在第一个函数中,我调用了对象上的一个方法:

button1.onclick=function()
{
    //Since we are calling a function on the object button1,
    //  in this function this = button1 (as an object)
    alert(this.id);
};

因此CCD_ 11在这种情况下是对象CCD_。

在另一个函数中,我定义了一个对象必须传递到的全局函数:

function testFunction(passedObject)
{
    // In this function, we pass the object 'this' from button2
    // If I now call passedObject.id, it will give the id of the passed object
    // In this case that is 'button2'
    alert(passedObject.id);
}

在该函数中,没有this。但是,我可以通过在HTML代码中的对象内调用this来将对象传递给此函数。

例如:

<button id="button2" onclick="testFunction(this)">Button 2</button>

所以现在我调用testFunction(this),并将对象<button id="button2">Button 2</button>作为参数传递。

总结一下:

  • 在对象内,this指对象本身
  • 在对象外部,this表示最近的父对象
  • 在对对象调用的方法中,this指代对象本身

总结这种行为的一句话很好:

在JavaScript中,它总是指我们正在执行的函数的"所有者",或者更确切地说,指函数所属的对象

一个更好的方法是调用函数TimeChangeView上的apply/call方法。apply/调用接受两个参数this对象和函数所需的任何参数(请注意,第二个参数可以是可选的(。例如,我们可以这样使用它TimeChangeView.apply(TimeChangeView(,它将这个值设置为TimeChangeView(记住JS中的函数是一个对象(。您还可以将TimeChangeView分配给一个变量,您可以使用该变量引用TimeChangeView中的函数。Ex

var timeChangeView=timeChangeView.apply(timeChangeView(;<''td onclick="timeChangeView.downHours((">

您还需要在TimeChangeView函数定义中返回this对象。