5

I'm new to JavaScript and since I come from strongly-typed languages I've chosen TypeScript.

I'd like to know what happens to variable red in Red getter in this code. Will it be recreated on every call (like in Green getter) or created once and used every time? Which is best?

class Color {
    public R: number;
    public G: number;
    public B: number;
    public A: number;

    static get Red(): Color {
        var red = new Color(255, 0, 0);
        Color.Red = function() { return red; }
        return red;
    }

    static get Green(): Color {
        return new Color(0, 255, 0);
    }

    constructor(red: number, green: number, blue: number, alpha: number = 255) {
        this.R = red;
        this.G = green;
        this.B = blue;
        this.A = alpha;
    }
}

3 Answers 3

9

The other answers are totally right but I think there's a subtle issue they're not mentioning. Because Red is defined as a getter it also gets an automatic empty setter that does nothing. So when you call Color.Red = function() { return red; } you're passing that function into the setter for Color.Red, which does nothing, so that statement has no effect. You can slap an alert() into the getter and call it a few times to see for yourself.

If you look at the generated JavaScript for this piece you'll see that the getter is created through Object.defineProperty, which is an interesting beast. You could make your own call to Object.defineProperty to redefine the action of the getter, but that seems like a lot of work when private static red : Color = new Color(255,0,0); works perfectly fine.

As for which is best, it's a question of trade offs and what's more important to you. Always returning a new Object is going to use up a lot more memory, but avoids the risk of somebody modifying Color.Green and causing a heck of a fun bug to track down.

Sign up to request clarification or add additional context in comments.

Comments

3

If you want to get it cached you can do:

class Color {
    public R: number;
    public G: number;
    public B: number;
    public A: number;

    private static _red : Color = new Color(255,0,0);   
    static get Red(): Color {
        return _red;
    } 

    static get Green(): Color {
        return new Color(0, 255, 0);
    }

    constructor(red: number, green: number, blue: number, alpha: number = 255) {
        this.R = red;
        this.G = green;
        this.B = blue;
        this.A = alpha;
    }
}

This way the constructor is not called each time you use Red.

Comments

1

Every time a getter is used, the function implementing it is invoked. The Red implementation isn't going to be accomplishing any sort of caching.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.