Created
September 23, 2014 13:53
-
-
Save yardfarmer/8ea0a2d1e9db263ba590 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="en"> | |
<head> | |
<title>JavaScript Patterns</title> | |
<meta charset="utf-8"> | |
</head> | |
<body> | |
<script> | |
/* Title: Inheritance by Copying Properties | |
Description: an object gets functionality from another object, simply by copying it | |
*/ | |
/* shallow copy, 'refernce object' is point the same address */ | |
function extend(parent, child) { | |
var i; | |
child = child || {}; | |
for (i in parent) { | |
if (parent.hasOwnProperty(i)) { | |
child[i] = parent[i]; | |
} | |
} | |
return child; | |
} | |
var dad = {name:"Adam"}; | |
var kid = extend(dad); | |
console.log(kid.name); // "Adam" | |
var dad = { | |
counts:[1, 2, 3], | |
reads:{paper:true} | |
}; | |
var kid = extend(dad); | |
kid.counts.push(4); | |
console.log(dad.counts.toString()); // "1,2,3,4" | |
console.log(dad.reads === kid.reads); // true | |
/* deep copy */ | |
function extendDeep(parent, child) { | |
var i, | |
toStr = Object.prototype.toString, | |
astr = "[object Array]"; | |
child = child || {}; | |
for (i in parent) { | |
if (parent.hasOwnProperty(i)) { | |
if (typeof parent[i] === 'object') { | |
child[i] = (toStr.call(parent[i]) === astr) ? [] : {}; | |
extendDeep(parent[i], child[i]); | |
} else { | |
child[i] = parent[i]; | |
} | |
} | |
} | |
return child; | |
} | |
var dad = { | |
counts:[1, 2, 3], | |
reads:{paper:true} | |
}; | |
var kid = extendDeep(dad); | |
kid.counts.push(4); | |
console.log(kid.counts.toString()); // "1,2,3,4" | |
console.log(dad.counts.toString()); // "1,2,3" | |
console.log(dad.reads === kid.reads); // false | |
kid.reads.paper = false; | |
// reference | |
// http://shop.oreilly.com/product/9780596806767.do | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment