Skip to content

Instantly share code, notes, and snippets.

@gibbok
Last active December 6, 2016 07:09
Show Gist options
  • Save gibbok/f0d3286f26c190b801160ad4c2e18902 to your computer and use it in GitHub Desktop.
Save gibbok/f0d3286f26c190b801160ad4c2e18902 to your computer and use it in GitHub Desktop.
GibboK - Pattern OLOO and pseudo-polymorphism
/*
Behavior delegation examples
OLOO (Objects Linking to Other Objects) pattern idea from Kyle Sypson
Example at: Delegating Widget Objects
https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch6.md
*/
// good example
var base = {
a : 3,
init: function(b, c) {
this.b = b || 1;
this.c = c || 2;
}
};
var obj = Object.create(base);
obj.init();
obj.d = '4';
obj.e = function(){};
alert(obj.hasOwnProperty('a')); //false (lookup protoype chain)
alert(obj.hasOwnProperty('b')); //true
alert(obj.hasOwnProperty('c')); //true
alert(obj.hasOwnProperty('d')); //true
alert(obj.hasOwnProperty('e')); //true
// bad example which use pseudo-polymorphism
var base2 = {
a: undefined,
b: undefined,
c: undefined,
init: function() {
}
};
var obj2 = Object.create(base2);
obj2.init();
alert(obj2.hasOwnProperty('b')); //false
obj2.b = '2';
alert(obj2.hasOwnProperty('b')); //true !!! ugly pseudo-polymorphism
obj2.d = function(){};
alert(obj2.hasOwnProperty('a')); //false
alert(obj2.hasOwnProperty('c')); //false
alert(obj2.hasOwnProperty('d')); //true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment