简体   繁体   中英

OOP javascript trying to access a method

I have writeen the ETF class. which is an attempt to write in OOP in javascript.

The class is called ETF. and the methods are getData and draw. I am trying to access method 'draw' from method '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..
        }

tried 'this.draw' but nothing..

anyone?

You need to assign "this" to a variable so you can access it within $.getJSON. If you tried to call the method using this.draw(lng_pr, sh_pr), "this" would be referring to the context of $.getJSON, not your current ETF object.

Here's how you'd do it:

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..
    }

Why don't you write the "class" like this:?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM