2

Can someone explain how this works. An object checks to see if it has been instantiated, and if it hasn't, then instantiates itself. It reminds me of a singleton, but I am not sure if I understand this code correctly.

var circularBuffer = function (size) {

    if (this instanceof  circularBuffer) {
        this.size = size;
        this.clear();
    } else {
        return new circularBuffer(size);
    }

};

1 Answer 1

3

This pattern makes sure that whether you call circularBuffer with new or not, you still get a new instance.

So both of the following result in a new circularBuffer instance being assigned to cb:

var cb = new circularBuffer(100);

var cb = circularBuffer(100);

In the first case, this is a circularBuffer instance so it follows the if path. In the second case, this is window so the method follows the else path and will re-call itself using new instead.

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

1 Comment

Wich is equivalent of this: var circularBuffer = function (size) { if (window.circularBuffer) { this.size = size; this.clear(); } else { return new circularBuffer(size); } };

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.