Declaring a TypeScript member in prototype, not appending to 'this'

Next TypeScript:

class A {
    member = "value";
}

      

... compiled for:

var A = (function () {
    function A() {
        this.member = "value";
    }
    return A;
})();

      

I want to achieve the following:

var A = (function () {
    function A() {
    }

    A.prototype.member = "value";

    return A;
})();

      

The reason for this is that I believe that the latter construct might be more efficient because (1) the assignment operator this.member = "value"

does not need to be executed every time a new instance is created, and (2) the memory payload of the instance will be less.

Disclaimer: I haven't downloaded these two constructs, so I really don't know if that's the case.

So my question is: Is it possible to declare a "prototype element" using a script type? ...

I would be happy if someone could explain why the script type is designed this way? ... (See §8.4.1 in the specification )

I understand that it would be silly to declare mutable members this way, but immutable primitive declarations like string

and number

should be okay to set on prototype, right?

Possible work could be:

class A {
    member: string;
}

A.prototype.member = "value";

      

However, this won't work for private users:

class A {
    private member: string;
}

A.prototype.member = "value"; // error TS2107: 'A.member' is inaccessible.

      

+3


source to share


2 answers


I came up with a possible job that works for private members too:

class A {
    private member: string;

    static __init = (() => {
        A.prototype.member = "value";
    })();
}

      



It's pretty good; all the code is inside the construct of the class and I have avoided casting before any

, so it is possible to keep track of references to those private members (for refactoring, etc.).

The dummy element is __init

declared in a class function when using this approach. Little problem.

+3


source


Is it possible to declare a "prototype element" using a script type?

At the moment, the language does not allow this.

Bypass

When the compiler is unhappy ... assert:

class A {
    private member: string;
}

(<any>A.prototype).member = "value"; // suppressed

      



why is the script type designed this way

Simply because it is non-idiomatic to have non-functions on prototype

.

(1) assigning this.member = "value" should not be done every time a new instance is created, and (2) the instance's memory payload will be smaller.

However, the search will definitely be slower. Here's a sample test: http://jsperf.com/prototype-vs-this-access

+5


source







All Articles