【发布时间】:2014-10-26 07:11:04
【问题描述】:
我目前正在尝试创建一个 HTML5 Canvas 游戏,我希望能够将功能附加到单击时激活的按钮。我可以为独特的功能执行此操作,但在循环使用具有预定义功能的许多按钮时,我正在努力寻找一种方法。
我已经创建了一个示例来展示我到目前为止所做的尝试:
jsFiddle:http://jsfiddle.net/ra1rb74w/1/
// The class that we want to create an array of
myClass = function() {
this.aFunction;
};
myClass.prototype = {
// Add a new function to this class
addFunction: function (newFunction) {
this.aFunction = newFunction;
},
// Use the current function
useFunction: function () {
if (this.aFunction != null) {
this.aFunction;
}
}
};
// The base function we will use in the classes
var baseFunction = function(x) { console.log(x); }
// Create the array of classes
var myClasses = [];
// Add 10 classes to the array and add a function to each of them
for (var x = 0; x < 10; x++) {
myClasses.push(new myClass());
myClasses[x].addFunction(baseFunction(x));
}
// Use the function in the first class
myClasses[0].useFunction();
您可以看到所有我不想要的函数都被触发,并且 useFunction() 函数不起作用。有没有办法做到这一点?
【问题讨论】:
-
哇。起初 - addFunction 期望函数作为参数(据我所知),但你会在那里推送未定义(作为调用 baseFunction 的结果)。并且 useFunction - 没有调用 aFunction(但我认为应该是) - 你想做什么?
-
喜欢这个jsfiddle.net/c7pkb0h6 ?
标签: javascript function loops