如何获取javascript类对象的属性值
我在从javascript类对象获取属性值时遇到困难。如何获取javascript类对象的属性值,javascript,class,Javascript,Class,我在从javascript类对象获取属性值时遇到困难。 以下是类文件以及我如何尝试获取其属性值: 1:我在classes.js中定义了一个名为School的类 export class School{ constructor() { this.schools = []; //to store schools returned from backend } //used to get all schools getall() {
以下是类文件以及我如何尝试获取其属性值: 1:我在classes.js中定义了一个名为School的类
export class School{
constructor()
{
this.schools = []; //to store schools returned from backend
}
//used to get all schools
getall()
{
axios.get('/api/schools')
.then(response =>{
this.schools = response.data;
console.error('School length: ' + this.schools.length);
this.ok = true;
//add origin data property
for(let i = 0; i < this.schools.length; i++)
{
this.schools[i]['orgValue'] = new tagChange();
}
})
.
catch(error => {
this.ok = false;
this.error = error.status;
this.schools = [];
});
return this.schools;
} //getall
}
3:调用getAllSchools()
方法后,mySchoolObj.schools
确实包含8个school元素,但是无法成功分配此.schools
,以下两个控制台.log
调用也只能打印零长度
4:我真的想知道如何将所有的
mySchoolObj.schools
返回到this.schools
,以及如何获取/访问它的其他属性值?axios.get
是异步的,这意味着当返回this.schools代码>,ajax调用尚未完成,因此返回一个空数组[]
更多信息请点击此处:
您可以返回axios
给出的承诺或使用回调,如下所示:
//used to get all schools
getall(callback) { // take a callback function
axios.get('/api/schools')
.then(response =>{
this.schools = response.data;
console.error('School length: ' + this.schools.length);
this.ok = true;
//add origin data property
for (let i = 0; i < this.schools.length; i++) {
this.schools[i]['orgValue'] = new tagChange();
}
if (typeof callback === 'function') {
callback(this.schools, null); // call the callback with data and null (null because there is no error)
}
})
.catch(error => {
this.ok = false;
this.error = error.status;
this.schools = [];
if (typeof callback === 'function') {
callback(null, error.status); // call the callback with null data and the error status
}
});
return this.schools;
}
methods: {
getAllSchools() {
this.mySchoolObj.getall((data, error) => {
if (error) {
return console.log(error);
}
this.schools = data;
console.log(this.schools);
});
}
},
(这段代码没有经过测试,它可能包含bug)“javascript类对象的属性值”--我的脑袋在转…那么你有什么改进的建议吗?了解javascript中的对象以及“类”在这种语言中的含义。并查看有关异步性的所有信息,以及针对特定情况的承诺(关于异步性的博客文章太多了!)。我引用的那个短语非常奇怪,因为它与语言的工作方式以及我们通常如何谈论它无关如果我从字面上理解上面引用的短语,那么您的代码将是错误的,您谈论的是构造函数对象本身的静态属性。此外,正如您所提到的,如何返回承诺
?您只需从getall()返回axios.get('/api/schools')
方法,并将其与getAllSchools()中的一些.then()
和.catch()
一起使用
methods: {
getAllSchools() {
this.mySchoolObj.getall((data, error) => {
if (error) {
return console.log(error);
}
this.schools = data;
console.log(this.schools);
});
}
},