使用KineticJS我想出了如何将一个函数作为Gameboard函数传递,但Gameboard函数中的所有内容都认为它现在是获得该函数的对象:(。
function Gameboard(){
//.... creates placeholders for stage layers and all objects
this.dice_layer=new Kinetic.Layer();
this.rolldice=function(){
alert(this.toString());
//..alter images
this.dice_layer.draw();//<~~ thinks this is circle once passed through setUpGameBoard says dice_layer is undefined. alert(this.toString()); shows this to be circle.
};
this.setUpGameBoard=function(){
// ...draws board pawns creates a circle object
var obj=this;//<~~ are there memory issues with this? Is there a better way?
circle.on("click",**obj**.rolldice.**bind**(obj);//** == ANSWER!!!!
};
};
答案 0 :(得分:1)
问题在于这一行:
this.doSomething=function(fnction){
您将doSomething
声明为具有单个参数fnction
的函数,但是当您调用它时,您传递的是两个 - 字符串和函数。
this.doSomething=function(str, fnction){
将按照您的预期行事。
根据您对第二个问题的“解决方案”,您似乎想要使用ES5的bind
。它允许您为特定函数调用指定this
,因为JavaScript实际上没有“方法”,您必须指定它们操作的对象。
this.barfoo.doSomething(this.doBar.bind(this));
可以将example of malfunctioning代码与fix with bind进行比较。
答案 1 :(得分:0)
可能您的简化并未显示真正的问题。我想以下类似于你的问题:
function foo(){
this.doSomething = function(fnction){
fnction();
};
}
function bar(){
this.myField = "Buzz"
this.barfoo = new foo();
this.doBar = function(){
alert(this.myField);
};
this.barfoo.doSomething(this.doBar); // tried this
//this.barfoo.doSomething(this.doBar()); also tried this
//this.barfoo.doSomething(bar.doBar); also tried this
//this.barfoo.doSomething(bar.doBar()); also tried this
}
您可以注意到访问this
相关属性的问题。
如果这确实是问题,那么您应该能够使用call
apply
方法中的foo
或doSomething
来解决问题:
function foo() {
this.doSomething = function (obj, fn) {
fn.call(obj);
};
}
这就是你在bar
中使用它的方式:
function bar() {
this.myField = "Buzz";
this.barfoo = new foo();
this.doBar = function () {
alert(this.myField);
};
this.barfoo.doSomething(this, this.doBar);
}
var myBar = new bar();
检查jsFiddle。