0

I have a confusion with Crockford recommended inheritance, what is the major difference between the Crockford method and the generic (default) way.

//Crockford method
      function object(o) {
            function F() {}
            F.prototype = o;
            return new F();
        }

The below is more generic way

function Base(name) {
    this.name = name;
}

Base.prototype.getName = function () {
    return 'Base :' + this.name;
}

function Child(name) {
    this.name = name;
}

Child.prototype.getName = function () {
    return 'Child :' + this.name;
}

function Kid(name) {
    this.name = name;
}

Kid.prototype.getName = function () {
    return 'Kid :' + this.name;
}

Child.prototype = new Base ("childBase");
Kid.prototype = new Child ("kidChild");

var base = new Base ("myBase");
var child = new Child("myChild");
var kid = new Kid("myKid");

console.log(base.getName());
console.log(child.getName());
console.log(kid.getName());

What is difference between the above two ?

Actually I am not able to completely understand Crockford method. Could any one help me to figure out the drawbacks in the generic way and advantages in Crockford method.

sokid
  • 813
  • 3
  • 10
  • 16
  • 1
    Did you actually had a look at the output? It should not be what you expect, since you are overriding the prototypes after you already assigned functions to them (`getName`). – Felix Kling Aug 04 '12 at 23:08
  • Have a look at [this answer](http://stackoverflow.com/a/1598077/1048572) – Bergi Aug 04 '12 at 23:23
  • 1
    @EliasVanOotegem: I would say a constructor (used with `new` keyword) *does create* inheritance chains... – Bergi Aug 04 '12 at 23:24
  • @Bergi, well everything does, really but the the Crockford's (rather dated) function allows you to create huge inheritance chains out of object literals, too. So there's no real need for the `new` keyword anymore – Elias Van Ootegem Aug 04 '12 at 23:28

1 Answers1

1
Child.prototype = new Base ("childBase");
Kid.prototype = new Child ("K1", "K2");

with these lines you instantiate two objects, which have even own names. What is that good for? In more complicated environments this potentially even breaks the application - when the Base constructor uses private variables and privileged methods, all its children will share the same variables in the same instance!

Therefore, one generally should not use this way but Crockfords function, the older version of Object.create. It will, called with Base.prototype, create a new object that inherits directly from this one - it only sets up the prototype chain, but does not execute any constructor code. Understanding Crockford's Object.create shim will help you with the details. The created object then is perfect to be the prototype object of the Children. Read also this answer.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375