Javascript 要在加载函数之外使用Clippy.JS的代理对象吗
我使用的是Clippy.JS,这是一个有趣的小Javascript库,它复活了MicrosoftsAssistant 说我想召唤巫师梅林:Javascript 要在加载函数之外使用Clippy.JS的代理对象吗,javascript,clippy,Javascript,Clippy,我使用的是Clippy.JS,这是一个有趣的小Javascript库,它复活了MicrosoftsAssistant 说我想召唤巫师梅林: clippy.load('Merlin', function(agent){ // do anything with the loaded agent agent.show(); agent.moveTo(100,100); agent.speak("Arthur, you are the chosen one to slay
clippy.load('Merlin', function(agent){
// do anything with the loaded agent
agent.show();
agent.moveTo(100,100);
agent.speak("Arthur, you are the chosen one to slay the dragon");
});
这是可行的,并且易于实现。当我想移动Merlin时,问题出现了:
$( "#target" ).click(function() {
agent.moveTo(333,333);
});
代理对象在此范围内没有初始化,我不知道加载代理对象后如何检索它
控制台显示此错误:
Uncaught ReferenceError: agent is not defined
代理不是全局变量,仅在代理回调函数中可用
要解决这个问题,您需要在回调函数之外创建一个变量,然后使用它全局地操作代理
以下几点应该行得通
//define the personal agent outside the callback function
let merlin;
clippy.load('Merlin', function(agent){
merlin = agent;
merlin.show();
merlin.moveTo(100,100);
merlin.speak("Arthur, you are the chosen one to slay the dragon");
});
$( "#target" ).click(function() {
merlin.moveTo(333,333);
});
因为代理不是全局变量。