rachsmithcodes / ama

Ask me anything!
53 stars 5 forks source link

Pattern Question #14

Closed HandsomeDan closed 8 years ago

HandsomeDan commented 8 years ago

Hey Rachel I had a quick question about a pattern I saw you use in this example:

function Circle(x,y,rad,color) {
    var _this = this;

    // constructor
    (function() {
        _this.x = x || null;
        _this.y = y || null;
        _this.radius = rad || null;
        _this.color = color || null;
    })();

    this.draw = function(ctx) {
        if(!_this.x || !_this.y || _this.radius || _this.color) {
            console.error('Circle requires an x, y, radius and color');
            return;
        }
        ctx.beginPath();
        ctx.arc(_this.x, _this.y, _this.radius, 0, 2 * Math.PI, false);
        ctx.fillStyle = _this.color;
        ctx.fill();
    }
}

What in the world is going on with the constructor here? For the life of me I can't figure out what pattern this is and what problem it's solving.

Anyway, I'm a huge fan of your tutorials over at codepen.

Thanks for taking the time to read this.

-- Dan

rachsmithcodes commented 8 years ago

Heya Dan! So, this was just a code organization habit that I had from my last job at Active Theory. In our JavaScript files/Classes we would always put the initial construction of the properties in an anonymous self-invoking function at the top - it was just so you had the visual grouping of the object properties there when you glanced at the file. So, no real benefit or reason for doing so - just a habit I had at the time :)

Thanks!