Skip to content

Instantly share code, notes, and snippets.

@leebyron
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leebyron/9504b80ade8d5a91c200 to your computer and use it in GitHub Desktop.
Save leebyron/9504b80ade8d5a91c200 to your computer and use it in GitHub Desktop.
How might "private methods" be transpiled to define a semantic behavior?
// Private methods (instance and static) are different from private properties
// because they are not assigned per instance. Instead, they can be thought of
// as a nested function, scoped to the class body.
// Resolution of a private `@x()` method can be done with brand checks, but
// inlined when the resolution can be determined statically.
class C {
m(somethingElse) {
somethingElse.@x();
somethingElse.@x.call(somethingElse);
@x.call(somethingElse);
@x();
C.@x();
}
@x() {
return this.m({});
}
static @x() {
return 'This is static';
}
}
// rough transpiled:
const C = function() {
function C() {}
C.prototype.m = function() {
// somethingElse.@x();
if (somethingElse === C) {
static_x.call(somethingElse);
} else if (somethingElse instanceof C) {
instance_x.call(somethingElse);
} else {
throw TypeError('Illegal access of private @x.');
}
// somethingElse.@x.call(somethingElse);
if (somethingElse === C) {
static_x.call(somethingElse);
} else if (somethingElse instanceof C) {
instance_x.call(somethingElse);
} else {
throw TypeError('Illegal access of private @x.');
}
// @x.call(somethingElse);
instance_x.call(somethingElse);
// @x();
instance_x.call(this);
// C.@x();
static_x.call(C);
}
function instance_x() {
return this.m();
}
function static_x() {
return 'This is static';
}
return C;
}();
@leebyron
Copy link
Author

One note here - if you can use .call/apply() then you might not be able to use the short-cut inline for a raw @x() or this.@x() because you can't guarantee the value of this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment