1

我已经编写了 ETF 类。这是在 javascript 中编写 OOP 的尝试。

该类称为ETF。方法是getData和draw。我正在尝试从方法“getData”访问方法“draw”

function ETF(){
    //global variable


}
//class methods => getData (from xml file), draw(draws the bar )
ETF.prototype ={
    getData: function(is_load, DateDiff){

        $.getJSON(
            "server/ETF.server.php",{
                mycase: 1
            },
            function(data){
                lng_pr  = data.longs_prec;
                sh_pr   = data.shorts_prec;
                ETF.draw(lng_pr, sh_pr); // <== how to access the draw method?
        });

    },//end getData
    //draw the 
    draw: function(lng_pr, sh_pr){
         //draw code..
        }

试过'this.draw'但没有..

任何人?

4

2 回答 2

1

您需要将“this”分配给一个变量,以便您可以在 $.getJSON 中访问它。如果您尝试使用 this.draw(lng_pr, sh_pr) 调用该方法,“this”将指的是 $.getJSON 的上下文,而不是您当前的 ETF 对象。

以下是你的做法:

function ETF(){
    //global variable


}
//class methods => getData (from xml file), draw(draws the bar )
ETF.prototype ={
    getData: function(is_load, DateDiff){
        var obj = this;  //assign current ETF object to a variable

        $.getJSON(
            "server/ETF.server.php",{
                mycase: 1
            },
            function(data){
                lng_pr  = data.longs_prec;
                sh_pr   = data.shorts_prec;
                obj.draw(lng_pr, sh_pr);  //will call your draw method below
        });

    },//end getData
    //draw the 
    draw: function(lng_pr, sh_pr){
         //draw code..
    }
于 2012-06-21T13:58:52.323 回答
-1

你为什么不这样写“类”:?

function ETF() {
    var that = this,
        /* holds the public methods / properties */
        thisObject = {};


    thisObject.getData = function(is_load, DateDiff){

        $.getJSON(
            "server/ETF.server.php",{
                mycase: 1
            },
            function(data){
                lng_pr  = data.longs_prec;
                sh_pr   = data.shorts_prec;
                thisObject.draw(lng_pr, sh_pr); // <== how to access the draw method?
        });

    };// end getData

    thisObject.draw = function(lng_pr, sh_pr){
         //draw code..
    };

    return thisObject;
}

var etfObject = new ETF();
于 2012-06-21T14:17:26.430 回答