Skip to content

Instantly share code, notes, and snippets.

@psiborg
psiborg / gist:1569649
Created January 6, 2012 08:17
JS Object Defaults 2
DEFAULTS = {
color: "blue",
border: 0,
width: '128px',
height: '128px'
};
function mergeOptions (defaults, options) {
for (var name in defaults) {
if (defaults.hasOwnProperty(name)) {
@psiborg
psiborg / gist:1569650
Created January 6, 2012 08:18
JS Object Defaults 1
function setBG (options) {
var args = {
red: 255,
green: 255,
blue: 255
}
// overwrite defaults
for (var i in options) {
args[i] = options[i];
@psiborg
psiborg / gist:1569652
Created January 6, 2012 08:18
JS Function Defaults
function say (name, agree) {
// provide default values
var name = name || "Fred";
var agree = (agree !== undefined) ? true : false;
}
say(); // Fred, false
say("Barney"); // Barney, false
say("Barney", "anything"); // Barney, true
@psiborg
psiborg / gist:1569659
Created January 6, 2012 08:20
JS Self-Invoking Function
(function () {
// self-invoking function
})();
@psiborg
psiborg / gist:1569660
Created January 6, 2012 08:20
JS Anonymous Inner Function
function outerFunction () {
return function () {
// anonymous inner function
}
}
@psiborg
psiborg / gist:1569661
Created January 6, 2012 08:21
JS Ajax
function getStockQuote() {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function () {
@psiborg
psiborg / gist:1569666
Created January 6, 2012 08:22
JS Objects
// object literal
var myObj = {
property1: 42,
property2: "Hello",
property3: true
};
// loop over properties
for (var i in myObj) {
console.log(i + ': ' + myObj[i]);
@psiborg
psiborg / gist:1569669
Created January 6, 2012 08:23
JS Arrays
// add items
[1, 2, 3].concat([4, [5, 6]]); // [1, 2, 3, 4, 5, 6]
[1, 2, 3].push([4, [5, 6]]); // [1, 2, 3, 4, [5, 6]]
[1, 2, 3].unshift([4, [5, 6]]); // [4, [5, 6], 1, 2, 3]
// remove items
[1, 2, 3].pop(); // [1, 2]
[1, 2, 3].shift(); // [2, 3]
@psiborg
psiborg / gist:1569671
Created January 6, 2012 08:23
JS URI
escape(str)
unescape(str)
encodeURI(str)
decodeURI(str)
encodeURIComponent(str)
decodeURIComponent(str)
var url = "http://finance.yahoo.com/q?s=RIM.TO&ql=0";
@psiborg
psiborg / gist:1569672
Created January 6, 2012 08:24
JS Strings
"abcde".charAt(3); // d
"abcde".charCodeAt(0); // 100 = d
String.fromCharCode(100); // d
"abcde".slice(0, 2); // ab
"abcde".slice(1, -1); // bcd
"abcde".slice(-2); // de
"abcde".substr(0, 2); // ab
"abcde".substr(1, 3); // bcd