0
我正在編寫一個腳本,使我可以創建一個上傳文件的對象,並且應該有方法來獲取屬性,例如上傳的文件的總大小,讓我告訴你:Javascript返回變量值形式的對象
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
}
我試圖改造讓變量分爲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.
我真的希望你能幫助我,謝謝你!
在函數內部,你得到一個新的'this',不再是你想要的外部函數。閱讀胖箭頭關閉。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_binding_of_this https://stackoverflow.com/questions/28371982/what-does-this-refer-to-in -arrow-functions-in-es6 – Thilo
如何創建實例?確保在使用'this.'賦值的版本中使用'new'。你怎麼稱呼'getSrcs'?這將決定什麼'這'是... – trincot
謝謝你thilo我會檢查出來。 –