有人知道为什么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;
};
});外部函数在其闭包中声明一个变量“外部”,该变量对内部函数自然是可见的。
发布于 2013-02-01 09:31:11
这是TypeScript中的一个bug,直到包含从那时起就被修复了的verion0.8.2。
发布于 2012-10-29 09:04:52
缩短到仅仅突出的几点:
这就是我认为你期待的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是警报语句中的一个问题,但还是编译了正确的JavaScript。您可以在http://typescript.codeplex.com中将其作为一个bug来引发。
https://stackoverflow.com/questions/13109413
复制相似问题