【问题标题】:OOP javascript trying to access a methodOOP javascript 试图访问一个方法
【发布时间】:2012-06-21 13:16:45
【问题描述】:

我已经编写了 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”但没有任何效果..

有人吗?

【问题讨论】:

  • 请详细说明ETF 类、draw 方法应该做什么以及遇到什么错误。
  • 你希望别人怎么理解你在这里想要做什么?
  • 我正在尝试从方法“getData”访问方法“draw”

标签: javascript oop methods


【解决方案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..
    }

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 这个问题是类的方法将为类的每个实例重新创建。如果您使用 OP 发布的原型模式,则不会发生这种情况,您只会获得所有对象都将引用的一组方法。虽然 IMO 不应该被否决,因为你的答案会起作用,而且它需要的额外内存并不是什么大问题。
    • @JoshNoe 很公平。感谢您的解释。今天学到了一些新东西。
    猜你喜欢
    • 1970-01-01
    • 2016-06-18
    • 2011-10-27
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    相关资源
    最近更新 更多