[英]Strange typescript error:“ the name g does not exist in the current scope”
[英]TypeScript closure scope error: The name does not exist in the current scope
有谁知道为什么test1无法编译?
class Y { public myMethod: any; };
class QQ { public test(name, fun: () => any) { } }
var qq = new QQ();
qq.test("Run test1", () => {
var outer = 10;
Y.prototype.myMethod = () => {
// Error: The name 'outer' does not exist in the current scope
outer = 11;
}
});
但是以下工作原理:
qq.test("Run test2", () => {
var outer = 10;
var fun = ()=> { outer = 11; };
Y.prototype.myMethod = fun;
});
所需代码的JavaScript版本如下所示:
qq.test("Run test1", function () {
var outer = 10;
Y.prototype.myMethod = function () {
outer = 11;
};
});
外部函数在其闭包内声明一个变量“外部”,该变量自然应对内部函数可见。
缩短到重点:
我认为这是您所期望的JavaScript。
var Y = (function () {
function Y() { }
Y.prototype.myMethod = function () {
};
return Y;
})();
var QQ = (function () {
function QQ() { }
QQ.prototype.test = function (name, fun) {
fun();
};
return QQ;
})();
var qq = new QQ();
qq.test("Run test1", function () {
var _this = this;
_this.outer = 10;
Y.prototype.myMethod = function () {
alert(_this.outer);
};
});
var y = new Y();
y.myMethod();
您需要更改TypeScript才能获得以下输出:
class Y {
public myMethod() {
}
}
class QQ {
public test(name, fun: () => any) { // updated signature
fun(); // call the function
}
}
var qq = new QQ();
qq.test("Run test1", () => {
this.outer = 10; // use this.
Y.prototype.myMethod = () => {
alert(this.outer);
}
});
var y = new Y();
y.myMethod();
是的,TypeScript认为this.outer
是Alert语句中的一个问题,但无论如何this.outer
编译正确的JavaScript。 您可以在http://typescript.codeplex.com上将其作为错误提出。
这是TypeScript中的一个错误,直到版本0.8.2 才被修复 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.