GeneratorFunction() constructor
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2016.
Warning: Các đối số được truyền cho hàm tạo này được phân tích cú pháp và thực thi động như JavaScript. Các API như thế này được gọi là injection sinks, và là vectơ tiềm năng cho các cuộc tấn công cross-site-scripting (XSS).
Bạn có thể giảm thiểu rủi ro này bằng cách luôn truyền các đối tượng TrustedScript thay vì chuỗi và thực thi trusted types.
Xem Các cân nhắc bảo mật trong tài liệu tham khảo hàm tạo Function() để biết thêm thông tin.
Hàm tạo GeneratorFunction() tạo các đối tượng GeneratorFunction.
Lưu ý rằng GeneratorFunction không phải là đối tượng toàn cục. Nó có thể được lấy bằng đoạn code sau:
const GeneratorFunction = function* () {}.constructor;
Hàm tạo GeneratorFunction() không được thiết kế để sử dụng trực tiếp, và tất cả các cảnh báo được đề cập trong mô tả Function() đều áp dụng cho GeneratorFunction().
Cú pháp
new GeneratorFunction(functionBody)
new GeneratorFunction(arg1, functionBody)
new GeneratorFunction(arg1, arg2, functionBody)
new GeneratorFunction(arg1, arg2, /* …, */ argN, functionBody)
GeneratorFunction(functionBody)
GeneratorFunction(arg1, functionBody)
GeneratorFunction(arg1, arg2, functionBody)
GeneratorFunction(arg1, arg2, /* …, */ argN, functionBody)
Note:
GeneratorFunction() có thể được gọi có hoặc không có new. Cả hai đều tạo ra một thực thể GeneratorFunction mới.
Tham số
Xem Function().
Ví dụ
Lưu ý rằng các ví dụ này bỏ qua việc sử dụng trusted types để ngắn gọn. Để xem code minh họa cách tiếp cận được khuyến nghị, hãy xem Sử dụng TrustedScript trong eval().
Tạo và sử dụng hàm tạo GeneratorFunction()
const GeneratorFunction = function* () {}.constructor;
const g = new GeneratorFunction("a", "yield a * 2");
const iterator = g(10);
console.log(iterator.next().value); // 20
Đặc điểm kỹ thuật
| Specification |
|---|
| ECMAScript® 2027 Language Specification> # sec-generatorfunction-constructor> |