Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use chained prototype inheritance in javascript?

perf

Why do we build a prototype inheritance chain rather then using object composition. Looking up through the prototype for each step in the chain get's expensive.

Here is some dummy example code :

var lower  = {
    "foo": "bar"
};

var upper = {
    "bar": "foo"
};

var chained = Object.create(lower,  pd(upper));

var chainedPrototype = Object.create(chained);

var combinedPrototype = Object.create(pd.merge(lower, upper));

var o1 = Object.create(chainedPrototypes);
var o2 = Object.create(combinedPrototypes);

uses pd because property descriptors are verbose as hell.

o2.foo is faster then o1.foo since it only goes up two prototype chain rather then three.

Since travelling up the prototype chain is expensive why do we construct one instead of using object composition?

Another better example would be :

var Element = {
  // Element methods
}

var Node = {
  // Node methods
}

var setUpChain = Object.create(Element, pd(Node));
var chained = Object.create(setUpChain);
var combined = Object.create(pd.merge(Node, Element));

document.createChainedElement = function() {
  return Object.create(chained);
}

document.createCombinedElement = function() {
  return Object.create(combined);
}

I do not see any code merging prototype objects for efficiency. I see a lot of code building chained prototypes. Why is the latter more popular?

The only reason I can think of is using Object.isPrototypeOf to test for individual prototypes in your chain.

Apart from isPrototypeOf are there clear advantages to using inheritance over composition?

like image 792
Raynos Avatar asked Sep 03 '11 16:09

Raynos


1 Answers

The main reason would have to be changes to the prototype object. A change to an ancestor object will be reflected across the entire chain. This could, conceivably, be a benefit. Though I can't immediately think of any real-world instances, I think embracing this dynamic nature could provide a dynamic that other (read: class-based) languages simply don't provide.

Objects further up the prototype chain could evolve as needed across the lifetime of an application, and those changes would be reflected across all descendant objects. This could be easily combined with JavaScript's functions as first-class objects to dynamically modify functionality as needed.

That said, if this functionality is not necessary, there is no reason to use the prototype chain over composition.

like image 76
Ryan Kinal Avatar answered Oct 14 '22 22:10

Ryan Kinal