mousePressed方法在p5js中提前启动
问题描述:
我使用p5.js创建了以下函数,并且mousePressed方法在页面加载时立即触发。它不会等待我点击按钮对象来显示包含ans变量的段落。mousePressed方法在p5js中提前启动
我在做什么错?
function setup() {
var ans = generate();
var checkMe = createButton('Check Answer');
checkMe.mousePressed(createP(ans));
}
答
让我们来看看这条线仔细一看:
checkMe.mousePressed(createP(ans));
这可以被分成两行:
var createPValue = createP(ans);
checkMe.mousePressed(createPValue);
换句话说,你打电话createP()
函数,然后传递返回的值(可能是undefined
)转换为mousePressed()
函数。我很惊讶这不会导致JavaScript控制台中的错误。
相反,您要做的是将函数作为值传递给mousePressed()
函数。既然你需要使用一个参数,你可以做到这一点是这样的:
function callCreateP(){
createP(ans);
}
checkMe.mousePressed(callCreateP);
注意callCreateP
没有括号()
它的名字后,当我们把它传递到mousePressed()
功能。这是因为我们将它用作值而不是直接调用它。
你可以缩短,为这条线:
checkMe.mousePressed(function(){ createP(ans); });
你是男人,凯文。它像一个魅力。额外的解释也很棒。我一直在与回调的概念斗争。但你真的更清楚了。谢谢!! – GMath314