我正在尝试创建一个构造函数,该函数包含对indexedDB或localStorage的调用,以检索某些数据(如果存在),然后从缓存或给定(默认)数据填充其值。
我有它的工作,但以某种方式破坏了我的代码。鉴于我的编程方法是“用棍子砸它直到起作用”,该代码绝对是一团糟。因此,我将问题简化为一个人为的示例,该示例以相同的方式失败。
删除异步函数(setTimeout)可以解决此问题,但是我的代码将无法工作。
var person = (function(){
function privateFn (value){
return value;
}
function private_asyncFn(value, callback){
setTimeout(function () {
return callback(value);
}, 10);
}
var DATA, NUM;
var personConstructor = function(name, age, gender, callback){
this.name = privateFn(name);
this.gender = privateFn(gender);
DATA = DATA || [];
NUM = NUM || 0;
this.num = NUM;
private_asyncFn(age, function(ret){
DATA[NUM++] = { name: this.name, age: ret };
if (callback instanceof Function) return callback(this.name);
}.bind(this));
};
personConstructor.prototype.getAge = function () {
if (this.gender === "male") return DATA[this.num].age;
else return DATA[this.num].age < 20 ? 18 : (Math.floor(DATA[this.num].age / 10) - 1) + "9 and holding";
};
return personConstructor;
})();
var name1;
var person1 = new person("jill", 32, "female", function(name){
name1 = name;
});
var age1 = person1.getAge(); //Uncaught TypeError: Cannot read property 'age' of undefined????
我在SO上使用类和Promise以及async / await看到了其他代码,但是我不知道它们是如何工作的,所以这段代码有点“老派”,对此感到抱歉。
在此示例中,您可以在初始化新人员之后立即检索该人员的年龄吗?
通过将所有异步逻辑移动到init
创建a之后调用的函数,new person
可以使构造函数保持同步。然后getAge
可以init
使用this.getAge()
或从回调函数内部进行调用person1.getAge()
(因为person1现在存在)
var person = (function(){
function privateFn (value){
return value;
}
function private_asyncFn(value, callback){
setTimeout(function () {
return callback(value);
}, 10);
}
var DATA, NUM;
//removed all data inputs and callback from constructor function
var personConstructor = function(){
//initialise publically accessible data
this.name = null;
this.gender = null;
//initialise blank data store
DATA = DATA || [];
NUM = NUM || 0;
this.num = NUM;
DATA[NUM++] = {
age: null
};
};
//created new init function
personConstructor.prototype.init = function (name, age, gender, callback){
this.name = privateFn(name);
this.gender = privateFn(gender);
private_asyncFn(age, function(ret){
DATA[this.num].age = ret;
//note: .call(this,...) on the callback to use "this" in the callback
if (callback instanceof Function) return callback.call(this, this.name);
}.bind(this));
};
personConstructor.prototype.getAge = function () {
if (this.gender === "male") return DATA[this.num].age;
else return DATA[this.num].age < 20 ? 18 : (Math.floor(DATA[this.num].age / 10) - 1) + "9 and holding";
};
return personConstructor;
})();
var name1, age1;
var person1 = new person();
person1.init("jill", 32, "female", function(name){
name1 = name;
age1 = this.getAge();
console.log(age1);//29 and holding, YES!
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句