[英]TypeScript closure scope error: The name does not exist in the current scope
does anyone know why test1 fails to compile? 有谁知道为什么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;
}
});
But the following works: 但是以下工作原理:
qq.test("Run test2", () => {
var outer = 10;
var fun = ()=> { outer = 11; };
Y.prototype.myMethod = fun;
});
The JavaScript version of the required code would look look like this: 所需代码的JavaScript版本如下所示:
qq.test("Run test1", function () {
var outer = 10;
Y.prototype.myMethod = function () {
outer = 11;
};
});
The outer function declares a variable "outer" within its closure, which should naturally be visible to the inner function. 外部函数在其闭包内声明一个变量“外部”,该变量自然应对内部函数可见。
Shortened to just the salient points: 缩短到重点:
This is the JavaScript I think you are expecting. 我认为这是您所期望的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();
You need to change your TypeScript to get this output: 您需要更改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();
And yes, TypeScript believes this.outer
to be a problem in the alert statement, but compiles the correct JavaScript anyway. 是的,TypeScript认为
this.outer
是Alert语句中的一个问题,但无论如何this.outer
编译正确的JavaScript。 You can raise that as a bug at http://typescript.codeplex.com . 您可以在http://typescript.codeplex.com上将其作为错误提出。
这是TypeScript中的一个错误,直到版本0.8.2 才被修复 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.