2017-08-06 18 views
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.

我真的希望你能幫助我,謝謝你!

+0

在函數內部,你得到一個新的'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

+0

如何創建實例?確保在使用'this.'賦值的版本中使用'new'。你怎麼稱呼'getSrcs'?這將決定什麼'這'是... – trincot

+0

謝謝你thilo我會檢查出來。 –

回答

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); 
} 

這是我發現的最簡單的例子。我希望它能幫助你。