gpt4 book ai didi

JavaScript:定义函数和实例化对象的顺序

转载 作者:行者123 更新时间:2023-11-29 10:48:28 30 4
gpt4 key购买 nike

我对定义函数和实例化对象的顺序有疑问,请参阅:JSFiddle

我现在只是在玩弄一个想法,但我碰壁了,我不知道是否有任何简单的解决方案来解决这个问题。基本上我有一个对象在另一个对象上有一些方法,但是这个另一个对象包含对第一个对象的引用,所以无论我实例化/定义什么顺序我都会得到一个错误,因为一个或另一个没有被加载:

  var router = {
update: function(event, from, to) {
window.location.hash = "#/" + to;
$("back-btn").disabled = fsm.can("back"); // *** And here I am referencing fsm
$("next-btn").disabled = fsm.can("next");
},
location: window.location.hash.substring(2),
}

var fsm = StateMachine.create({
initial: "intro",
events: [

// Next events and where to route based on our page
{ name: "next", from: "intro", to: "getname" },
{ name: "next", from: "getname", to: "welcome" },
{ name: "next", from: "welcome", to: "why" },

// We can't go "back" from the initial route
{ name: "back", from: "getname", to: "intro" },
{ name: "back", from: "welcome", to: "getname" },
{ name: "back", from: "why", to: "welcome" } ],

callbacks: {
onintro : router.update, //*** Here I am referencing the router object
ongetname: router.update,
onwelcome: router.update,
onwhy : router.update
}
});

感谢您的帮助。

最佳答案

你可以使用 try/catch 来避免第一个未定义的:

try {
$("back-btn").disabled = fsm.can("back");
$("next-btn").disabled = fsm.can("next");
} catch(e){}

此外,如果您在 JSFiddle 中进行所有测试,它会将您的 JS 包装到 window.onload 函数中。因此,当您单击按钮时,它们将尝试调用 fsm.back()fsm.next(),其中 fsm 是在 window.onload 函数的范围内定义。不在这些按钮可以访问的范围内。

关于JavaScript:定义函数和实例化对象的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14793443/

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