Meta programming

Starting with ECMAScript 2015, JavaScript gains support for the Proxy and Reflect objects allowing you to intercept and define custom behavior for fundamental language operations (e.g. property lookup, assignment, enumeration, function invocation, etc). With the help of these two objects you are able to program at the meta level of JavaScript.

代理

Introduced in ECMAScript 6, Proxy objects allow you to intercept certain operations and to implement custom behaviors.

For example, getting a property on an object:

let handler = {
  get: function(target, name) {
    return name in target? target[name] : 42
  }
}
let p = new Proxy({}, handler)
p.a = 1
console.log(p.a, p.b) // 1, 42
				

Proxy object defines a target (an empty object here) and a handler object, in which a get trap is implemented. Here, an object that is proxied will not return undefined when getting undefined properties, but will instead return the number 42 .

Additional examples are available on the Proxy reference page.

Terminology

The following terms are used when talking about the functionality of proxies.

handler
Placeholder object which contains traps.
traps
The methods that provide property access. (This is analogous to the concept of traps in operating systems.)
target
Object which the proxy virtualizes. It is often used as storage backend for the proxy. Invariants (semantics that remain unchanged) regarding object non-extensibility or non-configurable properties are verified against the target.
invariants
Semantics that remain unchanged when implementing custom operations are called invariants . If you violate the invariants of a handler, a TypeError will be thrown.

Handlers and traps

The following table summarizes the available traps available to Proxy objects. See the reference pages for detailed explanations and examples.

Handler / trap Interceptions Invariants
handler.getPrototypeOf() Object.getPrototypeOf()
Reflect.getPrototypeOf()
__proto__
Object.prototype.isPrototypeOf()
instanceof
  • getPrototypeOf method must return an object or null .
  • target is not extensible, Object.getPrototypeOf( proxy ) method must return the same value as Object.getPrototypeOf( target ) .
handler.setPrototypeOf() Object.setPrototypeOf()
Reflect.setPrototypeOf()
target is not extensible, the prototype parameter must be the same value as Object.getPrototypeOf( target ) .
handler.isExtensible() Object.isExtensible()
Reflect.isExtensible()
Object.isExtensible( proxy ) must return the same value as Object.isExtensible( target ) .
handler.preventExtensions() Object.preventExtensions()
Reflect.preventExtensions()
Object.preventExtensions( proxy ) only returns true if Object.isExtensible( proxy ) is false .
handler.getOwnPropertyDescriptor() Object.getOwnPropertyDescriptor()
Reflect.getOwnPropertyDescriptor()
  • getOwnPropertyDescriptor must return an object or undefined .
  • A property cannot be reported as non-existent if it exists as a non-configurable own property of target .
  • A property cannot be reported as non-existent if it exists as an own property of target and target is not extensible.
  • A property cannot be reported as existent if it does not exists as an own property of target and target is not extensible.
  • A property cannot be reported as non-configurable if it does not exist as an own property of target or if it exists as a configurable own property of target .
  • The result of Object.getOwnPropertyDescriptor( target ) can be applied to target 使用 Object.defineProperty and will not throw an exception.
handler.defineProperty() Object.defineProperty()
Reflect.defineProperty()
  • A property cannot be added if target is not extensible.
  • A property cannot be added as (or modified to be) non-configurable if it does not exist as a non-configurable own property of target .
  • A property may not be non-configurable if a corresponding configurable property of target exists.
  • If a property has a corresponding target object property, then Object.defineProperty( target , prop , descriptor ) will not throw an exception.
  • In strict mode, a false value returned from the defineProperty handler will throw a TypeError 异常。
handler.has()
Property query
foo in proxy
Inherited property query
foo in Object.create( proxy )
Reflect.has()
  • A property cannot be reported as non-existent, if it exists as a non-configurable own property of target .
  • A property cannot be reported as non-existent if it exists as an own property of target and target is not extensible.
handler.get()
Property access
proxy [foo]
proxy .bar
Inherited property access
Object.create( proxy )[foo]
Reflect.get()
  • The value reported for a property must be the same as the value of the corresponding target property if target 's property is a non-writable, non-configurable data property.
  • The value reported for a property must be undefined if the corresponding target property is non-configurable accessor property that has undefined as its [[Get]] 属性。
handler.set()
Property assignment
proxy [foo] = bar
proxy .foo = bar
Inherited property assignment
Object.create( proxy )[foo] = bar
{jsxref("Reflect.set()")}}
  • Cannot change the value of a property to be different from the value of the corresponding target property if the corresponding target property is a non-writable, non-configurable data property.
  • Cannot set the value of a property if the corresponding target property is a non-configurable accessor property that has undefined as its [[Set]] 属性。
  • In strict mode, a false return value from the set handler will throw a TypeError 异常。
handler.deleteProperty()
Property deletion
delete proxy [foo]
delete proxy .foo
Reflect.deleteProperty()
A property cannot be deleted if it exists as a non-configurable own property of target .
handler.enumerate()
Property enumeration / for...in :
for (let name in proxy ) {...}
Reflect.enumerate()
enumerate method must return an object.
handler.ownKeys() Object.getOwnPropertyNames()
Object.getOwnPropertySymbols()
Object.keys()
Reflect.ownKeys()
  • The result of ownKeys is a List.
  • The Type of each result List element is either String or Symbol .
  • The result List must contain the keys of all non-configurable own properties of target .
  • target object is not extensible, then the result List must contain all the keys of the own properties of target and no other values.
handler.apply() proxy(..args)
Function.prototype.apply() and Function.prototype.call()
Reflect.apply()
There are no invariants for the handler .apply 方法。
handler.construct() new proxy(...args)
Reflect.construct()
The result must be an Object .

Revocable Proxy

Proxy.revocable() method is used to create a revocable Proxy object. This means that the proxy can be revoked via the function revoke and switches the proxy off.

Afterwards, any operation on the proxy leads to a TypeError .

let revocable = Proxy.revocable({}, {
  get: function(target, name) {
    return '[[' + name + ']]'
  }
})
let proxy = revocable.proxy
console.log(proxy.foo)  // "[[foo]]"
revocable.revoke()
console.log(proxy.foo)  // TypeError is thrown
proxy.foo = 1           // TypeError again
delete proxy.foo        // still TypeError
typeof proxy            // "object", typeof doesn't trigger any trap
				

反射

Reflect is a built-in object that provides methods for interceptable JavaScript operations. The methods are the same as those of the proxy handlers .

Reflect is not a function object.

Reflect helps with forwarding default operations from the handler to the target .

With Reflect.has() for example, you get the in operator as a function:

Reflect.has(Object, 'assign') // true
				

A better apply function

In ES5, you typically use the Function.prototype.apply() method to call a function with a given this value and arguments provided as an array (or an array-like object ).

Function.prototype.apply.call(Math.floor, undefined, [1.75])
				

With Reflect.apply this becomes less verbose and easier to understand:

Reflect.apply(Math.floor, undefined, [1.75])
// 1
Reflect.apply(String.fromCharCode, undefined, [104, 101, 108, 108, 111])
// "hello"
Reflect.apply(RegExp.prototype.exec, /ab/, ['confabulation']).index
// 4
Reflect.apply(''.charAt, 'ponies', [3])
// "i"
				

Checking if property definition has been successful

With Object.defineProperty , which returns an object if successful, or throws a TypeError otherwise, you would use a try...catch block to catch any error that occurred while defining a property. Because Reflect.defineProperty returns a Boolean success status, you can just use an if...else block here:

if (Reflect.defineProperty(target, property, attributes)) {
  // success
} else {
  // failure
}
				
  1. JavaScript
  2. 教程:
  3. 完整初学者
    1. JavaScript 基础
    2. JavaScript 第一步
    3. JavaScript 构建块
    4. 引入 JavaScript 对象
  4. JavaScript 指南
    1. 介绍
    2. 语法和类型
    3. 控制流程和错误处理
    4. 循环和迭代
    5. 函数
    6. 表达式和运算符
    7. 数字和日期
    8. 文本格式
    9. 正则表达式
    10. Indexed collections
    11. Keyed collections
    12. Working with objects
    13. 对象模型的细节
    14. Using promises
    15. 迭代器和生成器
    16. Meta programming
    17. JavaScript 模块
  5. 中间体
    1. 引入 JavaScript 对象
    2. 客户端侧 Web API
    3. 重新介绍 JavaScript
    4. JavaScript 数据结构
    5. 相等比较和相同
    6. 闭包
  6. 高级
    1. 继承和原型链
    2. 严格模式
    3. JavaScript 类型数组
    4. 内存管理
    5. 并发模型和事件循环
  7. 参考:
  8. 内置对象
    1. AggregateError
    2. Array
    3. ArrayBuffer
    4. AsyncFunction
    5. AsyncIterator
    6. Atomics
    7. BigInt
    8. BigInt64Array
    9. BigUint64Array
    10. Boolean
    11. DataView
    12. Date
    13. Error
    14. EvalError
    15. Float32Array
    16. Float64Array
    17. Function
    18. Generator
    19. GeneratorFunction
    20. Infinity
    21. Int16Array
    22. Int32Array
    23. Int8Array
    24. InternalError
    25. Intl
    26. Intl.Collator
    27. Intl.DateTimeFormat
    28. Intl.DisplayNames
    29. Intl.ListFormat
    30. Intl.Locale
    31. Intl.NumberFormat
    32. Intl.PluralRules
    33. Intl.RelativeTimeFormat
    34. Iterator
    35. JSON
    36. Map
    37. Math
    38. NaN
    39. Number
    40. Object
    41. Promise
    42. Proxy
    43. RangeError
    44. ReferenceError
    45. Reflect
    46. RegExp
    47. Set
    48. SharedArrayBuffer
    49. String
    50. Symbol
    51. SyntaxError
    52. TypeError
    53. TypedArray
    54. URIError
    55. Uint16Array
    56. Uint32Array
    57. Uint8Array
    58. Uint8ClampedArray
    59. WeakMap
    60. WeakSet
    61. WebAssembly
    62. decodeURI()
    63. decodeURIComponent()
    64. encodeURI()
    65. encodeURIComponent()
    66. escape()
    67. eval()
    68. globalThis
    69. isFinite()
    70. isNaN()
    71. null
    72. parseFloat()
    73. parseInt()
    74. undefined
    75. unescape()
    76. uneval()
  9. 表达式 & 运算符
    1. 算术运算符
    2. Array comprehensions
    3. 赋值运算符
    4. Bitwise operators
    5. 逗号运算符
    6. Comparison operators
    7. 条件 (三元) 运算符
    8. Destructuring assignment
    9. Expression closures
    10. Function expression
    11. Generator comprehensions
    12. Grouping operator
    13. Legacy generator function expression
    14. Logical operators
    15. Nullish coalescing operator
    16. Object initializer
    17. 运算符优先级
    18. Optional chaining
    19. Pipeline operator
    20. 特性访问器
    21. 传播句法
    22. 异步函数表达式
    23. await
    24. class expression
    25. delete operator
    26. function* 表达式
    27. in operator
    28. instanceof
    29. new operator
    30. new.target
    31. super
    32. this
    33. typeof
    34. void 运算符
    35. yield
    36. yield*
  10. 语句 & 声明
    1. Legacy generator function
    2. async function
    3. block
    4. break
    5. class
    6. const
    7. continue
    8. debugger
    9. default
    10. do...while
    11. empty
    12. export
    13. for
    14. for await...of
    15. for each...in
    16. for...in
    17. for...of
    18. 函数声明
    19. function*
    20. if...else
    21. import
    22. import.meta
    23. label
    24. let
    25. return
    26. switch
    27. throw
    28. try...catch
    29. var
    30. while
    31. with
  11. 函数
    1. 箭头函数表达式
    2. 默认参数
    3. 方法定义
    4. 其余参数
    5. 自变量对象
    6. getter
    7. setter
    1. Class fields
    2. 构造函数
    3. extends
    4. static
  12. 错误
    1. Error: Permission denied to access property "x"
    2. InternalError: too much recursion
    3. RangeError: argument is not a valid code point
    4. RangeError: invalid array length
    5. RangeError: invalid date
    6. RangeError: precision is out of range
    7. RangeError: radix must be an integer
    8. RangeError: repeat count must be less than infinity
    9. RangeError: repeat count must be non-negative
    10. ReferenceError: "x" is not defined
    11. ReferenceError: assignment to undeclared variable "x"
    12. ReferenceError: can't access lexical declaration`X' before initialization
    13. ReferenceError: deprecated caller or arguments usage
    14. ReferenceError: invalid assignment left-hand side
    15. ReferenceError: reference to undefined property "x"
    16. SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
    17. SyntaxError: "use strict" not allowed in function with non-simple parameters
    18. SyntaxError: "x" is a reserved identifier
    19. SyntaxError: JSON.parse: bad parsing
    20. SyntaxError: Malformed formal parameter
    21. SyntaxError: Unexpected token
    22. SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
    23. SyntaxError: a declaration in the head of a for-of loop can't have an initializer
    24. SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
    25. SyntaxError: for-in loop head declarations may not have initializers
    26. SyntaxError: function statement requires a name
    27. SyntaxError: identifier starts immediately after numeric literal
    28. SyntaxError: illegal character
    29. SyntaxError: invalid regular expression flag "x"
    30. SyntaxError: missing ) after argument list
    31. SyntaxError: missing ) after condition
    32. SyntaxError: missing : after property id
    33. SyntaxError: missing ; before statement
    34. SyntaxError: missing = in const declaration
    35. SyntaxError: missing ] after element list
    36. SyntaxError: missing formal parameter
    37. SyntaxError: missing name after . operator
    38. SyntaxError: missing variable name
    39. SyntaxError: missing } after function body
    40. SyntaxError: missing } after property list
    41. SyntaxError: redeclaration of formal parameter "x"
    42. SyntaxError: return not in function
    43. SyntaxError: test for equality (==) mistyped as assignment (=)?
    44. SyntaxError: unterminated string literal
    45. TypeError: "x" has no properties
    46. TypeError: "x" is (not) "y"
    47. TypeError: "x" is not a constructor
    48. TypeError: "x" is not a function
    49. TypeError: "x" is not a non-null object
    50. TypeError: "x" is read-only
    51. TypeError: 'x' is not iterable
    52. TypeError: More arguments needed
    53. TypeError: Reduce of empty array with no initial value
    54. TypeError: X.prototype.y called on incompatible type
    55. TypeError: can't access dead object
    56. TypeError: can't access property "x" of "y"
    57. TypeError: can't assign to property "x" on "y": not an object
    58. TypeError: can't define property "x": "obj" is not extensible
    59. TypeError: can't delete non-configurable array element
    60. TypeError: can't redefine non-configurable property "x"
    61. TypeError: cannot use 'in' operator to search for 'x' in 'y'
    62. TypeError: cyclic object value
    63. TypeError: invalid 'instanceof' operand 'x'
    64. TypeError: invalid Array.prototype.sort argument
    65. TypeError: invalid arguments
    66. TypeError: invalid assignment to const "x"
    67. TypeError: property "x" is non-configurable and can't be deleted
    68. TypeError: setting getter-only property "x"
    69. TypeError: variable "x" redeclares argument
    70. URIError: malformed URI sequence
    71. Warning: -file- is being assigned a //# sourceMappingURL, but already has one
    72. Warning: 08/09 is not a legal ECMA-262 octal constant
    73. Warning: Date.prototype.toLocaleFormat is deprecated
    74. Warning: JavaScript 1.6's for-each-in loops are deprecated
    75. Warning: String.x is deprecated; use String.prototype.x instead
    76. Warning: expression closures are deprecated
    77. Warning: unreachable code after return statement
  13. 杂项
    1. JavaScript technologies overview
    2. 词汇语法
    3. JavaScript 数据结构
    4. Enumerability and ownership of properties
    5. Iteration protocols
    6. 严格模式
    7. Transitioning to strict mode
    8. Template literals
    9. 弃用特征