gpt4 book ai didi

javascript - 使用 this 从嵌套函数内部获取值

转载 作者:行者123 更新时间:2023-11-28 14:20:21 25 4
gpt4 key购买 nike

我有一段代码,其中一个主函数中有两个嵌套函数。

如何使用 this 关键字检索嵌套函数?可能吗?

我尝试过 times().present()new times().present() ,它们似乎都不起作用并返回 undefined

我在 w3School 上找到了类似的例子但在这种情况下似乎无法实现它。

提前致谢。

function times() {
var timingObj = function() {
this.present = currentTime;
this.past = pastTime;
};

var currentTime = function() {
var hourMin = new Date().getHours() + ":" + new Date().getMinutes();
return hourMin;
};

var pastTime = function() {
if (new Date().getDay() == 5) {
return "07:40"
} else {
return "16:30"
}
};
return timingObj;
}

console.log(times().present());
//console.log(new times().present());

最佳答案

function times() {
var currentTime = function() {
var hourMin = new Date().getHours() + ":" + new Date().getMinutes();
return hourMin;
};

var pastTime = function() {
if (new Date().getDay() == 5) {
return "07:40"
} else {
return "16:30"
}
};

return {
present: currentTime,
past: pastTime
};
}

console.log(times().present())

关于javascript - 使用 this 从嵌套函数内部获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55417100/

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