Monday, May 20, 2024
39
rated 0 times [  42] [ 3]  / answers: 1 / hits: 29072  / 9 Years ago, wed, april 22, 2015, 12:00:00

Does Kyle Simpson's "OLOO (Objects Linking to Other Objects) Pattern" differ in any way from the the Prototype design pattern? Other than coining it by something that specifically indicates "linking" (the behavior of prototypes) and clarifying that there's no to "copying" happening here (a behavior of classes), what exactly does his pattern introduce?


Here's an example of Kyle's pattern from his book, "You Don't Know JS: this & Object Prototypes":


var Foo = {
init: function(who) {
this.me = who;
},
identify: function() {
return "I am " + this.me;
}
};

var Bar = Object.create(Foo);

Bar.speak = function() {
alert("Hello, " + this.identify() + ".");
};

var b1 = Object.create(Bar);
b1.init("b1");
var b2 = Object.create(Bar);
b2.init("b2");

b1.speak(); // alerts: "Hello, I am b1."
b2.speak(); // alerts: "Hello, I am b2."

More From » design-patterns

 Answers
49

what exactly does his pattern introduce?




OLOO embraces the prototype chain as-is, without needing to layer on other (IMO confusing) semantics to get the linkage.



So, these two snippets have the EXACT same outcome, but get there differently.



Constructor Form:



function Foo() {}
Foo.prototype.y = 11;

function Bar() {}
Bar.prototype = Object.create(Foo.prototype);
Bar.prototype.z = 31;

var x = new Bar();
x.y + x.z; // 42


OLOO Form:



var FooObj = { y: 11 };

var BarObj = Object.create(FooObj);
BarObj.z = 31;

var x = Object.create(BarObj);
x.y + x.z; // 42


In both snippets, an x object is [[Prototype]]-linked to an object (Bar.prototype or BarObj), which in turn is linked to third object (Foo.prototype or FooObj).



The relationships and delegation are identical between the snippets. The memory usage is identical between the snippets. The ability to create many children (aka, many objects like x1 through x1000, etc) is identical between the snippets. The performance of the delegation (x.y and x.z) is identical between the snippets. The object creation performance is slower with OLOO, but sanity checking that reveals that the slower performance is really not an issue.



What I argue OLOO offers is that it's much simpler to just express the objects and directly link them, than to indirectly link them through the constructor/new mechanisms. The latter pretends to be about classes but really is just a terrible syntax for expressing delegation (side note: so is ES6 class syntax!).



OLOO is just cutting out the middle-man.



Here's another comparison of class vs OLOO.


[#66964] Monday, April 20, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
turnerf

Total Points: 620
Total Questions: 101
Total Answers: 109

Location: French Polynesia
Member since Tue, Jul 7, 2020
4 Years ago
;