Created
August 28, 2012 23:57
-
-
Save rauschma/3505466 to your computer and use it in GitHub Desktop.
@ operator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Based on: http://wiki.ecmascript.org/doku.php?id=strawman:syntactic_support_for_private_names | |
//// The at (@) operator | |
// Intuitively: | |
// - obj.@foo is syntactic sugar for obj[foo] | |
// - @foo is syntactic sugar for [foo] (for method definitions, property definitions, etc.) | |
// Usage: Let propName be a normal variable holding either a symbol or a string. | |
// - Property access: obj.@propName | |
// - Property definition (object literal): @propName: propValue | |
// - Method definition (class, object literal): @propName(...) { ... } | |
// - Getter definition (class, object literal): get @propName() { ... } | |
// - Setter definition (class, object literal): set @propName(x) { ... } | |
// - Generator method definition (class, object literal): *@propName(x) { ... } | |
//// Declare symbols (e.g.): | |
public myPublicSymbol; // or `name` or `symbol` | |
// Equivalent: let myPublicSymbol = new Name(true) | |
private myPrivateSymbol; | |
// Equivalent: let myPrivateSymbol = new Name() | |
// optional: class-internal declarations and other features proposed by Allen | |
//// Example: object literal | |
private foo, bar, baz, bam; | |
let obj = { | |
@foo: "a data property", | |
@bar() {return "a concise method property"}, | |
get @baz() {return "a get accessor"}, | |
*@bam(n) {yield 0; return n} //a generator method | |
}; | |
console.log(obj.@foo); // a data property | |
//// Example: classes | |
private x, y; | |
public validate; | |
class Point { | |
get x() {return this.@x} | |
set x(v) {this.@x = this.@validate(v)} | |
get y() {return this.@y} | |
set y(v) {this.@y = this.@validate(v)} | |
@validate(value) { | |
if (typeof value !== "number") throw TypeError("number expected"); | |
return value; | |
} | |
constructor (x,y) { | |
this.x = x; | |
this.y = y; | |
} | |
}; | |
class QIPoint extends Point{ | |
@validate(value) { | |
super.@validate(value); | |
if (value<0) throw RangeError("negative values not accepted"); | |
return value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment