4

So here's the object 'playerTurnObj'

function playerTurnObj(set_turn) {
    this.playerTurn=set_turn;
    function setTurn(turnToSet) {
        this.playerTurn=turnToSet;
    }
    function getTurn() {
        return this.playerTurn;
    }
}

and here is what I'm doing with it

var turn = new playerTurnObj();
turn.setTurn(1);

so I try to make the script do the setTurn() method in playerTurnObj() to save a 'turn' in a game I'm making. The problem is, it does not do the turn.setTurn(1); part because I keep getting the error above

what am I doing wrong? I searched, but I could not find an exact answer to my question.


Passing parameters to function before this.control() in Ext-JS 4

I have this:

{
    listeners['combobox[name="counterparty_id"]'] = {
        afterrender: {
            fn: this.onComboboxCounterpartyAfterrender,
            scope: this
        }
    };      

    this.control(listeners);
}



// function which is being called after rendering the combobox

onComboboxCounterpartyAfterrender: function(combobox, eOpts){

// some code

},

So, how can I send additional parameteres to onComboboxCounterpartyAfterrender function?

Maybe something like this:

listeners['combobox[name="counterparty_id"]'] = {
            afterrender: {
                fn: this.onComboboxCounterpartyAfterrender,
                scope: this,
                params: someParameters
            }
        };
4

3 回答 3

1

这不是 JavaScript 的工作方式。您的“构造函数”函数包含在 . 范围之外不可见的内联函数playerTurnObj。因此,您的变量turn没有setTurn定义方法,因为错误消息正确说明。可能你想要这样的东西:

function playerTurnObj(set_turn) {
    this.playerTurn=set_turn;
}

playerTurnObj.prototype = {
    setTurn: function(turnToSet) {
        this.playerTurn=turnToSet;
    },
    getTurn: function() {
        return this.playerTurn;
    }
};

现在您的变量turn有两个方法setTurngetTurn它们对您使用创建的实例进行操作new

于 2013-05-18T12:08:13.673 回答
1

setTurnandgetTurn函数是私有的,所以它们返回undefined而不是调用函数。你可以做:

function playerTurnObj(set_turn) {
    this.playerTurn=set_turn;
    this.setTurn = setTurn;
    this.getTurn = getTurn;

    function setTurn(turnToSet) {
        this.playerTurn=turnToSet;
    }
    function getTurn() {
        return this.playerTurn;
    }
}

然后,您拥有public setTurngetTurn方法,并且可以按如下方式调用它们:

var turn = new playerTurnObj();
turn.setTurn(1);

http://jsfiddle.net/Ht688/

于 2013-05-18T12:10:17.403 回答
0

我从中得出的结论是,您需要在函数 playerTurnObj() 中返回对象 this。所以你的新代码看起来像:

function playerTurnObj(set_turn) {
    this.playerTurn=set_turn;
    function setTurn(turnToSet) {
        this.playerTurn=turnToSet;
    }
    function getTurn() {
        return this.playerTurn;
    }
    return this;
}
于 2013-05-18T12:10:20.963 回答