gpt4 book ai didi

javascript - OOP javascript 尝试访问方法

转载 作者:行者123 更新时间:2023-11-28 09:50:27 24 4
gpt4 key购买 nike

我已经编写了 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”但什么也没有..

有人吗?

最佳答案

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

关于javascript - OOP javascript 尝试访问方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11139046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com