试图访问方法的OOP javascript
我写了ETF课程。这是一个用javascript编写OOP的尝试 这门课叫做ETF。方法有getData和draw。试图访问方法的OOP javascript,javascript,oop,methods,Javascript,Oop,Methods,我写了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, DateD
我正在尝试从方法“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..
}
功能ETF(){
//全局变量
}
//类方法=>getData(来自xml文件),draw(绘制条形图)
ETF.prototype={
getData:函数(是加载,日期差异){
$.getJSON(
“server/ETF.server.php”{
我的病例:1
},
功能(数据){
lng_pr=data.longs_prec;
sh_pr=data.shorts_prec;
ETF.draw(lng_-pr,sh_-pr);//您需要将“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();
功能ETF(){
var=这个,
/*保存公共方法/属性*/
thisObject={};
thisObject.getData=函数(为加载,日期差异){
$.getJSON(
“server/ETF.server.php”{
我的病例:1
},
功能(数据){
lng_pr=data.longs_prec;
sh_pr=data.shorts_prec;
thisObject.draw(lng\U pr,sh\U pr);//请详细说明ETF
类、draw
方法应该做什么,以及您遇到了什么错误。您到底是如何期望任何人理解您在这里试图做什么的?我试图从方法“getData”访问方法“draw”。问题是该类的方法将被重新创建ted用于类的每个实例。如果您使用原型模式作为发布的OP,这不会发生,您只会得到一组所有对象都将引用的方法。尽管IMO不应该投反对票,因为您的答案会起作用,而且所占用的额外内存也不是什么大问题。@JoshNoe,这很公平。感谢您的解释。今天学到了一些新东西。