gpt4 book ai didi

javascript - 在 return 语句中访问 JS 函数

转载 作者:行者123 更新时间:2023-11-28 13:36:44 25 4
gpt4 key购买 nike

如何从以下代码中的 $(...) 访问函数 showDashboardshowTimeline

define(["jquery", "bootstrap", "./timeline"], function($, bootstrap, timeline) {

$(function(){

$("#right-menu-dashboard").click(function(){
// I would like to access the showDashboard function here...
showDashboard();
});

$("#right-menu-timeline").click(function(){
// ... and the showTimeline function here.
showTimeline();
});

return {

showDashboard: function() {
// Some code here
},

showTimeline: function() {
// And here too!
}
}
});

最佳答案

有几种方法。我可能会这样做:

define(["jquery", "bootstrap", "./timeline"], function($, bootstrap, timeline) {

$(function(){

$("#right-menu-dashboard").click(function(){
// I would like to access the showDashboard function here...
showDashboard();
});

$("#right-menu-timeline").click(function(){
// ... and the showTimeline function here.
showTimeline();
});

function showDashBoard() {
// Some code here
}

function showTimeline() {
// And here too!
}

return {
showDashboard: showDashboard,
showTimeline: showTimeline
};
});

但是这是可以做到这一点的最小 mod:

define(["jquery", "bootstrap", "./timeline"], function($, bootstrap, timeline) {

$(function(){
var obj;

$("#right-menu-dashboard").click(function(){
// I would like to access the showDashboard function here...
obj.showDashboard();
});

$("#right-menu-timeline").click(function(){
// ... and the showTimeline function here.
obj.showTimeline();
});

obj = {

showDashboard: function() {
// Some code here
},

showTimeline: function() {
// And here too!
}
};
return obj;
});

或者这可能会更干净一些(只是更少的最小模式):

define(["jquery", "bootstrap", "./timeline"], function($, bootstrap, timeline) {

$(function(){
var obj = {

showDashboard: function() {
// Some code here
},

showTimeline: function() {
// And here too!
}
};

$("#right-menu-dashboard").click(function(){
// I would like to access the showDashboard function here...
obj.showDashboard();
});

$("#right-menu-timeline").click(function(){
// ... and the showTimeline function here.
obj.showTimeline();
});

return obj;
});

但请注意,它们之间存在差异。例如,当您调用 showDashboard 时,在第一个中,this 将是全局对象(在松散模式下)或 undefined (在严格模式下)在通话期间。在后两个中,它将是您从 $ 返回的对象。如果您没有在这些函数中使用 this,也没关系;如果你是,那就是。

关于javascript - 在 return 语句中访问 JS 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20871808/

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