对于我正在进行的项目,我正在使用以下布局构建一些数据对象(这是我正在使用ArrayBuffers读取的二进制文件:
AFile.prototype = {
p: new BufferPack(),
filedata: null,
position: 0,
label_records: null,
closestmultipleof: function(n,v) {
return Math.ceil((v / n) * n);
},
r: function(size) {
result = new Uint8Array(this.filedata,this.position,size);
this.position += size;
return result;
}
readValueLabel: function() {
return {
value: this.rS(8),
len: this.rS8(),
label: this.rS(this.closestmultipleof(8, this.len + 1))
};
},
readLabelRecords: function() {
return {
rec_type: this.rS32(),
label_count: this.rS32(),
value_labels: _.map(_.range(this.label_count), function(num) {
console.debug(num);
},this)
};
},
loadFile: function(blob) {
this.filedata = blob;
this.label_records = this.readLabelRecords();
}
};
但是,我似乎在访问返回范围中的值时遇到问题。在某些返回作用域中,我需要访问同一作用域中的变量,以便稍微操作数据(参见value_labels的定义)。
只是,它似乎无法访问变量label_count(可能是因为它在相同的返回范围内)。我怎么能这样做?
我能让它发挥作用的唯一方法就是我这样做:
ret = {}
ret['a'] = 5;
ret['b'] = ret['a'] * 2
return ret;
但这看起来很丑陋。有什么想法吗?
是的,这是一个单身人士!我只会使用一次。
让我说清楚:问题在以下代码中:
return {
a: functionreturn(),
b: this.a * s
};
This.a似乎不存在。
答案 0 :(得分:1)
<强> [更新] 强> 您可以为label_count创建一个闭包。
function AFile(){};
AFile.prototype ={
readLabelRecords: function() {
label_count=this.rS32();
return {
label_count:label_count,
log:console.log(label_count)//'return from rs32'
};
},
};
AFile.prototype.rS32=function(){
return "return from rs32";
}
var o = new AFile();
o.readLabelRecords();
答案基于提供的代码,最简单的代码:
function complicatedCalculations(){
return 22;
}
function returnObject(){
var cacheComplicated=complicatedCalculations();//closure variable will
// be available within the entire body of returnObject function
// but never outside of it.
return{
calculated:cacheComplicated,
twiceCalculated:cacheComplicated*2//you could not access calculated
// here so using a cache closure variable
}
}
或者让returnObject函数返回使用构造函数创建的对象的新实例:
function returnObject(){
return new (function(){
this.calculated=complicatedCalculations();
this.twiceCalculated=this.calculated*2;
})();
}
答案 1 :(得分:0)
您忘记了readValueLabel
之前的逗号,这使得结构无效。
<强>更新强>:
太糟糕了,其他答案被删除了,即使它没有“编译”也有一个有效的点。
对this
的引用在JS的内部作用域内是有问题的,但它可以通过做类似的事情来解决:
readLabelRecords: function() {
var that = this;
return {
rec_type: that.rS32(),
label_count: that.rS32(),
value_labels: _.map(_.range(that.label_count), function(num) {
console.debug(num);
},that)
};
}