Skip to content

Instantly share code, notes, and snippets.

@fillano
Created May 14, 2012 10:47
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 fillano/2693260 to your computer and use it in GitHub Desktop.
Save fillano/2693260 to your computer and use it in GitHub Desktop.
demo for Javascript object clone and traits
<html>
<body>
<body>
</html>
<script>
function trait(spec) {
this.traits = {};
for(var i in spec) {
if(spec.hasOwnProperty(i)) {
if(spec[i]['deps']&&spec[i]['func']&&typeof spec[i]['func']==='function') {
if(typeof spec[i]['deps']==='object' && spec[i]['deps'].splice) {
this.traits[i] = spec[i];
}
}
}
}
this.applyto = function(target) {
for(var i in this.traits) {
if(this.traits.hasOwnProperty(i)) {
for(var j=0; j<this.traits[i].deps; j++) {
if(!target[this.traits[i].deps[j]]) {
break;
}
}
target[i] = this.traits[i].func;
}
}
}
};
function clone(source, target) {
for(var i in source) {
if(source.hasOwnProperty(i)&&!target[i]) {
target[i] = source[i];
}
}
return target;
}
var People = {
name: null,
height: null,
weight: null
}
var man1 = clone(People, {});
man1.name = "man1";
man1.height = "170cm";
man1.weight = "70kg";
var man2 = clone(People, {});
man2.name = "man2";
man2.height = "180cm";
man2.weight = "92cm";
var player = new trait(
{
introduce: {
deps: ['name','height','weight'],
func: function() {alert('Hi, my name is '+this.name+' and I\'m '+this.height+' height and the weight of '+this.weight+' is not important.');}
},
dunk: {
deps: ['name'],
func: function() {alert(this.name+' got 2 points.');}
}
}
);
player.applyto(man1);
player.applyto(man2);
man1.introduce();
man2.introduce();
man1.dunk();
man2.dunk();
man2.dunk();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment