gpt4 book ai didi

javascript - 如何在函数内调用函数而不将任何变量传递给函数 Javascript

转载 作者:行者123 更新时间:2023-12-01 03:38:16 24 4
gpt4 key购买 nike

我有以下代码,但它不断抛出“未捕获的类型错误:无法读取未定义的属性'nineAM'”

通常在 OOP 中我会声明一个类,然后在类中拥有单独的方法。我想使用 JS 做类似的事情,但不太确定这是否可能。

function SetBtnToEcr () {
document.getElementById("depart").value = "Test 1";
document.getElementById("arrive").value = "Test2";

GetTodaysDate();
new (GetHour()).nineAM();
}

function SetDeptTime () {
SetBtnToECR();
}

function GetHour(){
function nineAM () {
document.getElementById("hour").selectedIndex = "09";
}

function fiveThirtyPM(){
document.getElementById("hour").selectedIndex = "17";
document.getElementById("minute").selectedIndex = "30";
}

function twoFifteenPM(){
document.getElementById("hour").selectedIndex = "14";
document.getElementById("minute").selectedIndex = "15";
}
}

我在网上查看过,但在所有其他示例中,我看到参数被传递到方法中,或者只是返回字符串的方法,然后使用 this.methodName 返回所需的字符串。但是我不想返回任何东西,我只想将时间设置为上午 9 点。

最佳答案

如果您希望 GetHour 成为 constructor function (类似于类)它应该是这样的:

function GetHour(){
this.nineAM = function () {
document.getElementById("hour").selectedIndex = "09";
}
// ...
}

使用方式如下:

new GetHour().nineAM();

或者如果您使用ES2015或更高版本,您可以使用 classes 进行定义:

class GetHour {
nineAM() {
document.getElementById("hour").selectedIndex = "09";
}
}
new GetHour().nineAM();

关于javascript - 如何在函数内调用函数而不将任何变量传递给函数 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44084590/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com