proposal-attributes
A proposal for ECMA-262 that suggests the addition of Attributes feature.
Syntax
code:js
#ClassAttribute
class Foo {}
#FunctionAttribute
function foo() {}
class Foo {
#MethodAttribute
method() {
}
}
Attributes are EcmaScript classes which are attributed by Attribute attribute
code:javascript
#Attribute
class MyAttribute {}
The instance of an attribute is set to the attributed element, and can be retrieved by the well known symbol Symbol.attributes.
A class attribute
code:javascript
#MyAttribute
class Foo {}
const myAttr = FooSymbol.attributes
A function attribute
code:js
#MyFuncAttribute
function foo() {}
const myFuncAttr = fooSymbol.attributes
Transpile
Attributes are roughly transpiled as below
code:js
#Attribute
class MyAttribute {
}
#MyAttribute
class Foo {}
This transpiles into
code:js
Symbol.attributes ??= Symbol('Symbol.attributes')
if (typeof globalThis.Attribute === 'undefined') {
globalThis.Attribute = class Attribute {}
}
class MyAttribute {}
MyAttributeSymbol.attributes = new Attribute()
class Foo {}
if (!MyAttributesSymbol.attributes.some(attr => attr instanceof Attribute)) {
throw new TypeError('MyAttribute can\'t be used as Attribute because it is not an Attribute')
}
FooSymbol.attributes = new MyAttribute()
Prior Art
Attributes
PHP 8 Attributes https://stitcher.io/blog/attributes-in-php-8
Rust Attributes https://doc.rust-lang.org/reference/attributes.html
C# Attributes https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/
Decorators
Python Decorators https://www.python.org/dev/peps/pep-0318/
tc39/proposal-decorators https://github.com/tc39/proposal-decorators
Annotations
Java Annotations https://docs.oracle.com/javase/tutorial/java/annotations/basics.html
Scala Annotations https://docs.scala-lang.org/tour/annotations.html
Kotlin Annotations https://kotlinlang.org/docs/reference/annotations.html
Note
Anyone can fork, copy, or steal this document and/or idea.
Reference
Annotations vs Decorators https://github.com/tc39/proposal-decorators/issues/115
Metadata Reflection API https://github.com/rbuckton/reflect-metadata
#TC39 #JavaScript #decorators