Last active
August 29, 2015 14:12
-
-
Save mattlockyer/3aae8b4c06f32c24420f to your computer and use it in GitHub Desktop.
Minimal Implementation of Eric Elliot's Stampit
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
var OBJ = { | |
create:function(obj) { | |
return (function() { | |
var priv = {}; | |
var pub = { | |
__proto__:obj ? obj.__proto__ : {}, | |
setPriv:function(name, value) { | |
priv[name] = value; | |
}, | |
getPriv:function(name) { | |
return priv[name]; | |
} | |
}; | |
return pub; | |
})(); | |
}, | |
state:function(obj, name, value) { | |
obj[name] = value; | |
}, | |
method:function(obj, name, func) { | |
obj.__proto__[name] = func; | |
}, | |
enclose:function(obj, name, value) { | |
obj.setPriv(name, value); | |
}, | |
clone:function(obj) { | |
return OBJ.props(obj, OBJ.create(obj));; | |
}, | |
compose:function(arr) { | |
if (arr.length === 0) return; | |
var obj = OBJ.clone(arr[0]); | |
for (var i = 1; i < arr.length; i++) | |
obj = OBJ.props(arr[i], OBJ.protos(arr[i], obj)); | |
return obj; | |
}, | |
props:function(obj1, obj2){ | |
for (var name in obj1) | |
if (name !== 'setPriv' && name !== 'getPriv') obj2[name] = obj1[name]; | |
return obj2; | |
}, | |
protos:function(obj1, obj2) { | |
for (var name in obj1.__proto__) | |
obj2.__proto__[name] = obj1.__proto__[name]; | |
return obj2; | |
} | |
}; | |
var a = OBJ.create(); | |
a.name = 'matt'; | |
OBJ.method(a, 'foo', function() { | |
console.log(this.name); | |
}); | |
var b = OBJ.clone(a); | |
b.age = 32; | |
var c = OBJ.create(); | |
c.last = 'lock'; | |
var d = OBJ.compose([a, b, c]) | |
console.log(d.name); | |
console.log(d.last); | |
console.log(d.age); | |
d.foo(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wrote this after watching Eric Elliot's talk from JSConf EU.
Basically, you can
create objects
enclose and use private values through setPriv and getPriv
set methods
set properties
clone
and compose objects from multiple objects