Skip to content

Instantly share code, notes, and snippets.

@saltlakeryan
Forked from anonymous/gist:da20acbe0f0cc59afad7
Last active August 29, 2015 14:00
Show Gist options
  • Save saltlakeryan/0de437735feafcad78f0 to your computer and use it in GitHub Desktop.
Save saltlakeryan/0de437735feafcad78f0 to your computer and use it in GitHub Desktop.

From "Beginning Backbone.js":

function Message(subject, recipient, content) {
  this.subject = subject;
  this.recipient = recipient;
  this.content = content;
}

Message.prototype.show = function(){
        console.log('To:' + this.recipient + 'Subject: ' + this.subject + 'Message:' + this.content);
};

var myEmail = new Message('Javascript is cool', '[email protected]', 'Prototype is useful');

From "Data Structures and Algorithms with JavaScript":

function Stack() {
   this.dataStore = [];
   this.top = 0;
   this.push = push;
   this.pop = pop;
   this.peek = peek;
   this.clear = clear;
   this.length = length;
}

function push(element) {
   this.dataStore[this.top++] = element;
}

function peek() {
   return this.dataStore[this.top-1];
}

function pop() {
   return this.dataStore[--this.top];
}

function clear() {
   this.top = 0;
}

function length() {
   return this.top;
}

The following pattern protects from accidentally doing:

person = Person("frank");

without the new operator

    function Person(name) {
        if (this instanceof Person) {
            this.name = name;
        } else {
            // called without "new", throw exception or something...
        }
    }

    Person.prototype.sayName = function() {
        console.log(this.name);
    };
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();
    }
}
var testModule = (function () {
 
  var counter = 0;
 
  return {
 
    incrementCounter: function () {
      return counter++;
    },
 
    resetCounter: function () {
      console.log( "counter value prior to reset: " + counter );
      counter = 0;
    }
  };
 
})();
 
// Usage:
 
// Increment our counter
testModule.incrementCounter();
 
// Check the counter value and reset
// Outputs: 1
testModule.resetCounter();
@saltlakeryan
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment