gpt4 book ai didi

javascript - TypeScript 闭包范围错误 : The name does not exist in the current scope

转载 作者:行者123 更新时间:2023-11-28 02:38:13 28 4
gpt4 key购买 nike

有谁知道为什么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;
};
});

外部函数在其闭包内声明了一个变量“outer”,该变量自然应该对内部函数可见。

最佳答案

简化为仅突出要点:

这就是我认为您所期待的 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 .

关于javascript - TypeScript 闭包范围错误 : The name does not exist in the current scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13109413/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com