我正在编写一个脚本,使我能够创建一个上传文件的对象,并且应该有方法来获取属性,例如上传文件的总大小,让我告诉你:
function FileUploader = function (to){
let html = "some html with the form...";
to.append(html);
let input = 'someSelector...';
let allSizes = [];
let allSrcs = [];
let totalSize = 0;
input.on('change', function (){
//some validation
let data = new FormData();
//for loop to append the input files
let request = createRequest(); //createRequest returns a request...
request.addEventListener("load", function (evt){
for( let i = 0; i<input.files.length; i++){
totalSize+= input.files[i].size;
allSizes.push(input.files[i].size);
}
let response = JSON.parse(e.currentTarget.responseText);
for(let i = 0; i<response.length; i++){
allSrcs.push(response[i]);
}
alert("Ok");
);
//other request handlers
request.open("POST", 'someLocalPath');
request.send(data);
});
}
Uploader.prototype.getSrcs= function (){
//the problem comes here, I can't pass the value of any variable in the object
}
我尝试将let变量转换为this
分配,如下所示:
function FileUploader = function (to){
let html = "some html with the form...";
to.append(html);
let input = 'someSelector...';
this.allSizes = [];
this.allSrcs = [];
this.totalSize = 0;
input.on('change', function (){
//some validation
let request = createRequest(); //createRequest returns a request...
request.addEventListener("load", function (evt){
for( let i = 0; i<input.files.length; i++){
this.totalSize+= input.files[i].size;
this.allSizes.push(input.files[i].size);
}
let response = JSON.parse(e.currentTarget.responseText);
for(let i = 0; i<response.length; i++){
this.allSrcs.push(response[i]);
}
alert("Ok");
);
});
}
在最后一种情况下,我得到了未定义的错误,例如cannot read property push of undefined.
我真的希望你能帮助我,非常感谢你!
答案 0 :(得分:1)
对于每个寻求快速解决方案的人来说,这里都是一个易于理解的解决方案:
function Person() {
var that = this;
that.age = 0;
setInterval(function growUp() {
// The callback refers to the `that` variable of which
// the value is the expected object.
that.age++;
}, 1000);
}
这是我发现的最基本的例子。我希望它可以帮助你。