尝试访问方法的 OOP JavaScript

OOP javascript trying to access a method

本文关键字:OOP JavaScript 方法 访问      更新时间:2023-09-26

我已经写了ETF类,这是试图用javascript用OOP编写的。

该类称为ETF,方法是getData和draw。我正在尝试从方法"getData"访问方法"绘制"

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",但什么都没有。

任何人?

您需要将"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..
    }

你为什么不这样写"类":?

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();