DEV Community

Konstantinos Blatsoukas
Konstantinos Blatsoukas

Posted on

js inheritance (part 2: OLOO)


A short blog about how you can achieve "inheritance" in js (second part, it's more about behavior and property delegation).
In this part I will try to demonstrate and explain a different approach how you can achieve "inheritance" (a more accurate
term is "delegation").

I read this technique in Kyle Simpson's book: You do not know javascript: this & object prototypes.
I his book called this code style Objects linked to other objects (OLOO), which I found to be simple and elegant.

OLOO (Objects Linked to Other Objects, a different way of inheritance)

let's see this concept by investigating the following code example:

Alt Text

  1. First an object Team is created (literal syntax used)
  2. This object has three properties, all of them are behaviors
  3. In line 15, a new object is created, but this time by using the
    function Object.create() and as an argument the object Team.
    In this way the two objects are linked.
    Which means that the object messi can make use of the Team behaviors
    if the behaviors are not found in the object messi.
    So, those two objects are collaborators! We have a synergy between

  4. In line 17, a property called setTeamDetails is assigned to messi
    object. It is a behavior, that internally makes two calls in functions
    setTeamName and setTeamColor, which both are not properties of messi.

    But, because the objects messi and Team have established a synergy,
    the messi object will delegate the work to Team object!

  5. In line 22, messi calls the function setTeamDetails, which
    internally makes to calls on the Team object behaviors.
    This calls, assigns the properties teamName and teamColor to messi
    , by implicit call.
    (see more on my previous blog about this keyword a link)

  6. Finally, a call to showTeamInfo is made, again here messi object
    delegates to Team object (since the messi object doesn't has a property named showTeamInfo)

To sum up

  • Two objects can form a synergy/link, by using the Object.create() function
  • If some behavior is not found in one object, this object can delegates/look up this behavior in the other object that collaborates with. (This is one way relationship)
  • New properties can be assigned to an object by using another object (in our example, messi object used Team object to assign two new properties teamName and teamColor)


Top comments (0)