Javascript:调用存储在变量中的方法
我试图通过在一个上下文中创建一个方法并将其存储在全局变量中来利用 Javascript 闭包,以便稍后可以从另一个上下文中调用它。
//Global variable to hold the function
var revertEvent;
//creates the function and assigns it to the global variable
function createRevertFunction(eventToBeReverted) {
revertEvent = function () {
alert("Now Restoring Event");
$('#calendar').fullCalendar('renderEvent', eventToBeReverted, true);
}
}
因此,“createRevertFunction”保存原始对象的状态。调用此函数后,该对象“eventToBeReverted”会被修改,因此这提供了一种无需刷新页面即可将原始内容恢复到 UI 的方法。
我的问题是我似乎无法调用变量“revertEvent”中的函数。
我已经尝试过:
revertEvent();
revertEvent.call();
window[revertEvent]();
但都不起作用。任何帮助将不胜感激...!
I am trying to take advantage of Javascript closures by creating a method in one context and storing it in a global variable so that it may be called later from another context.
//Global variable to hold the function
var revertEvent;
//creates the function and assigns it to the global variable
function createRevertFunction(eventToBeReverted) {
revertEvent = function () {
alert("Now Restoring Event");
$('#calendar').fullCalendar('renderEvent', eventToBeReverted, true);
}
}
So, the "createRevertFunction" holds the state of the original object. That object "eventToBeReverted" is modified down the road after this function is called, so this provides a means to restore the original to the UI without page refresh.
My problem is that I can't seem to call the function in the variable "revertEvent".
I've tried:
revertEvent();
revertEvent.call();
window[revertEvent]();
and none of them work. Any help would be appreciated...!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为这里最可能的问题是您在通过
createRevertFunction
设置之前尝试调用revertEvent
。要验证此更改,请更改revertEvent
的声明,如下所示。如果在
createRevertFunction
之前调用,则会弹出“尚未看到”警报。I think the most likely problem here is that you're attempting to call
revertEvent
before it's been set viacreateRevertFunction
. To verify this change the declaration ofrevertEvent
as followsThis will pop up the alert "not seet yet" in the case it's called before
createRevertFunction
使 createRevertFunction 返回内部函数。分配。
make createRevertFunction return the interior function. Assign.
这对我有用。向我们展示您对函数
createRevertFunction
的用法...This works for me. Show us your usage of the function,
createRevertFunction
...revertEvent 仅在函数内部定义,之后就会被忘记。您必须将其保存到全局变量(在函数外部定义),或者返回创建的函数并存储它。
revertEvent is defined only inside your function and is forgotten afterwards. You will have to save it to a global variable (that is defined outside the function) or rather return the created function and store it.