传递Object方法的对象方法是什么语法?

时间:2013-01-12 14:01:03

标签: javascript

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


 };  

};

2 个答案:

答案 0 :(得分:1)

问题在于这一行:

    this.doSomething=function(fnction){

您将doSomething声明为具有单个参数fnction的函数,但是当您调用它时,您传递的是两个 - 字符串和函数。

    this.doSomething=function(str, fnction){

将按照您的预期行事。

jsFiddle demo


根据您对第二个问题的“解决方案”,您似乎想要使用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方法中的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