Created
August 31, 2011 20:47
-
-
Save ryanflorence/1184675 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
define({ | |
/* | |
* Simplified prototypal inheritance, see http://javascript.crockford.com/prototypal.html | |
*/ | |
create: function (obj){ | |
function F() {} | |
F.prototype = obj; | |
return new F(); | |
}, | |
/* | |
* Dynamic property setting | |
* for example | |
* var o = {}; | |
* object.set(o, 'a.b.c', 'foo'); | |
* console.log(o) // {a: {b: { c: 'foo' }}} | |
*/ | |
set: function (obj, property, value) { | |
var tree = obj, | |
split = property.split('.'), | |
last = split.pop(), | |
next; | |
while (next = split.shift()){ | |
if (typeof tree[next] !== 'object') tree[next] = {}; | |
tree = tree[next]; | |
} | |
tree[last] = value; | |
}, | |
/* | |
* Dynamically delete properties of an object, similar to above | |
* deletes the last property in the chain | |
* for example: | |
* var o = {a: { b: { c: { d: 'foo' }}}} | |
* object.unset(o, 'a.b.c'); | |
* o; // { a: {b: {} }} | |
*/ | |
unset: function (obj, property){ | |
var tree = obj, | |
split = property.split('.'), | |
last = split.pop(); | |
while (next = split.shift()) tree = tree[next]; | |
delete tree[last] | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage