Javascript Coffescript闭包\u此引用在嵌套循环中丢失
下面是我观察到的关于咖啡脚本的有趣内容 TLDR:{ 我们知道,胖箭头(Javascript Coffescript闭包\u此引用在嵌套循环中丢失,javascript,coffeescript,Javascript,Coffeescript,下面是我观察到的关于咖啡脚本的有趣内容 TLDR:{ 我们知道,胖箭头(=>)生成一个闭包,保存对this的引用,并且@的每个引用都将被this的原始值替换。因此,以下coffeescript代码: => @sth 将产生以下结果: (function(_this) { return (function() { return _this.sth; }); })(this); 注意\u this.sth } 但这是我发现的一个角落案例: => for a i
=>
)生成一个闭包,保存对this
的引用,并且@
的每个引用都将被this
的原始值替换。因此,以下coffeescript代码:
=>
@sth
将产生以下结果:
(function(_this) {
return (function() {
return _this.sth;
});
})(this);
注意\u this.sth
}
但这是我发现的一个角落案例:
=>
for a in sth
for b in @sth
sth
评估结果如下:
(function(_this) {
return (function() {
var a, b, i, len, results;
results = [];
for (i = 0, len = sth.length; i < len; i++) {
a = sth[i];
results.push((function() {
var j, len1, ref, results1;
ref = this.sth;
results1 = [];
for (j = 0, len1 = ref.length; j < len1; j++) {
b = ref[j];
results1.push(sth);
}
return results1;
}).call(_this));
}
return results;
});
})(this);
这是正常的行为,还是一个bug?更仔细地观察内部循环:
results.push((function() {
var j, len1, ref, results1;
ref = this.sth;
// Loop stuff goes here...
}).call(_this));
内部循环被包装在一个函数中(作为循环理解代码的一部分),该函数使用以下公式进行计算:
call()
方法使用给定的此值和单独提供的参数调用函数
调用
是通过\u this
调用的(从=>
中隐藏/绑定的
),因此该函数中的这个
实际上就是\u this
,一切都很好
如果通过显式不返回任何内容来抑制理解代码:
=>
for a in sth
for b in @sth
sth
return
然后您将看到您最初期望的ref=\u this.sth
:
(function(_this) {
return (function() {
var a, b, i, j, len, len1, ref;
for (i = 0, len = sth.length; i < len; i++) {
a = sth[i];
ref = _this.sth; # <---------------------------
for (j = 0, len1 = ref.length; j < len1; j++) {
b = ref[j];
sth;
}
}
});
})(this);
(函数(\u this){
返回(函数(){
变量a、b、i、j、len、len1、ref;
对于(i=0,len=sth.length;i(function(_this) {
return (function() {
var a, b, i, j, len, len1, ref;
for (i = 0, len = sth.length; i < len; i++) {
a = sth[i];
ref = _this.sth; # <---------------------------
for (j = 0, len1 = ref.length; j < len1; j++) {
b = ref[j];
sth;
}
}
});
})(this);