如何从类函数内部访问对象属性 [英] How to access object property from inside class function
问题描述
我的Java中的一个类有时需要与Json一起更新。我一直做一个函数,给定一个id来更新数据数组,但是现在我想做更多封装(函数更新,在类内部)。
one of my classes in Javascript needs to be "updated" with Json sometimes. I have always done a function, that updates the array of data, given an id, but now i wanted to do it more encapsulated (Function update, inside the class).
我做了什么:
function File(data){
this.data = data;
this.update = function (callback){
var set = function(ajaxData){
this.data = ajaxData.PcbFile;
}
getPcbFile(data.id, function(ajaxData){
set(ajaxData);
callback();
});
};
}
但是, this.data = ajaxData.PcbFile;
不起作用...我的对象仍然是最后一个数据集,而不是更新的数据集。我创建了SET函数,这是另一种尝试设置数据的尝试。
But, this.data = ajaxData.PcbFile;
doesen't work... My object still with the last data set, and not the updated one. The function SET, i created as another attempt to set the data.
在ajax上没有问题,因为我调试了ajaxData,这样就可以了(当我更新时)。
There is no problem on the ajax, since i debuged the ajaxData, and it's ok (when i update).
那么,我如何真正从内部函数访问对象属性 data
?
So, how do i really access the object property data
from an inside function?
(对不起我的英语...)
(sorry for my english...)
推荐答案
我很难学到方式,您必须小心 this
。它始终引用当前作用域中的 this
,而不是包含对象。每当将某些东西包装在 function(){...}
中时, this
的作用范围就会不同。在您的情况下,将对象复制到局部变量并操作它的 .data
属性。
I learned this the hard way, you have to be careful with this
. It always refers to the this
in the current scope, not it's containing object. Whenever you wrap something in function() { ... }
, this
becomes of a different scope. In your case, duplicate the object to a local variable and manipulate it's .data
property.
function File(data){
this.data = data;
var file = this; //call the variable whatever you want
this.update = function (callback){
var set = function(ajaxData){
file.data = ajaxData.PcbFile;
}
getPcbFile(data.id, function(ajaxData){
set(ajaxData);
callback();
});
};
}
这篇关于如何从类函数内部访问对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!