Skip to content

Instantly share code, notes, and snippets.

@cfleschhut
Created May 15, 2011 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cfleschhut/973622 to your computer and use it in GitHub Desktop.
Save cfleschhut/973622 to your computer and use it in GitHub Desktop.
JavaScript Patterns [O’Reilly]
/*
Chapter 3: Literals and Constructors
*/
// Object Constructor Catch
var o = new Object();
console.log(o.constructor.name);
var o = new Object(1);
console.log(o.constructor.name);
var o = new Object("str");
console.log(o.constructor.name);
var o = new Object(true);
console.log(o.constructor.name);
// Custom Constructor Functions
var Person = function(name) {
this.name = name;
this.say = function() {
return "I am " + this.name;
};
};
// Patterns for Enforcing new
// Self-Invoking Constructor
function Waffle() {
if (!(this instanceof Waffle)) {
return new Waffle();
}
this.tastes = "yummy";
}
Waffle.prototype.wantAnother = true;
var first = new Waffle(),
second = Waffle();
console.log(first.tastes, second.tastes);
console.log(first.wantAnother, second.wantAnother);
// Array Literal
// Check for Array-ness
if (!Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) === "[object Array]";
};
}
// JSON
// Working with JSON
var jstr = '{ "mykey": "my value" }';
var data = JSON.parse(jstr);
console.log(data.mykey);
var dog = {
name: "Fido",
dob: new Date(),
legs: [1,2,3,4]
};
var jsonstr = JSON.stringify(dog);
console.log(jsonstr);
// http://www.slideshare.net/stoyan/javascript-patterns
function mixInThese() {
var arg, prop, child = {};
for(arg = 0; arg<arguments.length; arg++) {
for(prop in arguments[arg]) {
child[prop] = arguments[arg][prop];
}
}
return child;
}
function extend(parent, child) {
var i, child = child || {};
for(i in parent) {
child[i] = parent[i];
}
return child;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment