0

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!!!!


 };  

};

4

2 に答える 2

1

問題はこの行です:

    this.doSomething=function(fnction){

doSomething単一のパラメーターを持つ関数として宣言していfnctionますが、それを呼び出すと、文字列と関数の2つを渡します。

    this.doSomething=function(str, fnction){

期待どおりに動作します。

jsFiddleデモ


2番目の問題の「解決策」に基づくと、ES5を使用したいようですbindthisJavaScriptには実際には「メソッド」がないため、特定の関数呼び出しのを指定できます。JavaScriptが操作するオブジェクトを指定する必要があります。

 this.barfoo.doSomething(this.doBar.bind(this));

誤動作しているコードの例はbindを使用した修正と比較できます。

于 2013-01-12T14:09:07.660 に答える
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関連するプロパティへのアクセスに関する問題に気付くことができる場所。

これが実際に問題である場合は、またはのいずれcallapplyの方法を使用して解決できるはずです。foodoSomething

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を確認してください。

于 2013-01-12T14:41:13.127 に答える