Function() constructor tạo Function object mới. Code string được parse khi function được tạo (không phải lúc define như function declaration/expression).
Ví dụ
<html>
<body>
<script>
var num = new Function('p', 'q', 'r', 'return p * q * r');
document.write("Value after multiplication: " + num(5, 2, 9)); // 90
</script>
</body>
</html>
Cú pháp
new Function([arg1[, arg2[, ...argN]],] functionBody)
- Tham số cuối cùng:
functionBody(string chứa JS code). - Các tham số trước: tên parameters (string, có thể comma-separated trong một string).
Đặc điểm & Cảnh báo
| Đặc điểm | Function Constructor | Function Declaration/Expression |
|---|---|---|
| Parsing | Runtime (mỗi lần new Function) | Parse time (compile time) |
| Scope | Chỉ global scope (không tạo closure với local scope) | Lexical scope (closure) |
| Performance | Chậm (parse mỗi lần tạo) | Nhanh (parsed once) |
| Security | Rủi ro XSS/injection nếu input từ user | An toàn |
| Debugging | Khó (anonymous, dynamic) | Dễ (có tên, source map) |
| Strict mode | Không tự động strict | Có thể "use strict" |
Ví dụ Scope Difference
const x = 10;
function normal() {
return x; // Closure: truy cập x = 10
}
const dynamic = new Function('return x;'); // Tìm x trong global scope
console.log(normal()); // 10
console.log(dynamic()); // ReferenceError: x is not defined (global không có x)
// Nếu global có x:
globalThis.x = 20;
console.log(dynamic()); // 20 (global x)
Khi nào dùng (hiếm)?
- Dynamic code generation từ trusted source (template engine, rule engine).
- Deserialize function từ config/storage (cẩn trọng security).
- Legacy code compatibility.
Best Practice
Tránh dùng Function Constructor trong ứng dụng bình thường. Dùng function declaration, expression, arrow function. Nếu cần dynamic function, cân nhắc eval() (cũng nguy hiểm) hoặc architecture khác (strategy pattern, plugin system).