cuốn sách gpt4 ai đã làm

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

In lại Tác giả: Walker 123 更新时间:2023-11-28 02:38:13 29 4
mua khóa gpt4 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”,该变量自然应该对内部函数可见。

câu trả lời hay nhất

简化为仅突出要点:

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

29 4 0
Walker 123
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress