gpt4 book ai didi

Javascript 从对象中返回变量值

转载 作者:行者123 更新时间:2023-12-03 03:43:06 27 4
gpt4 key购买 nike

我正在编写一个脚本,该脚本使我能够创建一个上传文件的对象,并且该对象应该具有获取属性(例如上传文件的总大小)的方法,让我向您展示:

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

在最后一种情况下,我收到未定义的错误,例如无法读取未定义的属性推送。

真心希望您能帮助我,非常感谢!

最佳答案

对于寻求易于理解的快速解决方案的每个人来说,这里有一个解决方案:

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

这是我找到的最基本的例子。希望对您有帮助。

关于Javascript 从对象中返回变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45529250/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com