Skip to content

Emit real private methods #14781

Closed
Closed
@zengfenfei

Description

@zengfenfei

In TS, private methods are inaccessible outside the defining class. But in emitted code, private methods are just ordinary JS methods which are accessible outside. I have a suggestion to emit real private methods for JS:

//*** TS code ***
class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
        this.invisible();
    }
    private invisible() {
        console.log(this.greeting);
        this.greeting = 'new value';
    }
}

//*** Currently Emitted Code ***
var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
        this.invisible();
    }
    Greeter.prototype.invisible = function () {
        console.log(this.greeting);
        this.greeting = 'new value';
    };
    return Greeter;
}());

//*** Suggested Emitted Code ***
var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
        invisible(this);
    }
    function invisible(self) {
        console.log(self.greeting);
        self.greeting = 'new value';
    };
    return Greeter;
}());

Now the emitted private methods are inaccessible from outside. Another benefits is, self (the alias of this) and the private method name can be minified and even inlined by tools like uglyfyjs and google closure.

I've been using this kind of way to implement JS private methods in my projects. Per my experience, I haven't run into any side effects. And there's not performance implication either, here is a blog about this: http://andrewkelley.me/post/js-private-methods.html

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions