12

Douglas Crockford seems to like the following inheritance approach:

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}
newObject = Object.create(oldObject);

It looks OK to me, but how does it differ from John Resig's simple inheritance approach?

Basically it goes down to

newObject = Object.create(oldObject);

versus

newObject = Object.extend();

And I am interested in theories. Implementation wise there does not seem to be much difference.

1

2 Answers 2

7

The approach is completely different, the Resig technique creates constructor functions, this approach is also known as classical inheritance i.e.:

var Person = Class.extend({
  init: function(isDancing){
    this.dancing = isDancing;
  }
});

var p = new Person(true);

As you see, the Person object is actually a constructor function, which is used with the new operator.

With the Object.create technique, the inheritance is based on instances, where objects inherit from other objects directly, which is also known as Prototypal Inheritance or Differential Inheritance.

Sign up to request clarification or add additional context in comments.

4 Comments

Just interested, what's your opinion on Crockford's approach? I could never quite understand the appeal of contructor-less instances...
@J-P: I really like Object.create it makes prototypal inheritance very simple, and you can build really clever creational patterns with it, and now with the ECMAScript 5th Edition, the standard compliant method can use property descriptors... very powerful...
So, why would one use one over another? I need to build a system and utilize some clever inheritance, but I do not see any reason to pick one over another.
@Tower: The pseudo-classical approach, like the Resig's simple inheritance, the base2 library or the approach of PrototypeJS can be easy to gasp by people used to work with classical languages, so it may depend on your team skills, IMO, I really like prototypal inheritance for its simplicity, but for sure, you'll need to start thinking prototypically. Another option can be the use plain constructors, but be sure to learn how they work.
6

They are completely different.

Douglas Crockford's method creates an instance that inherits a different instance.

John Resig's approach creates a class that inherits a different class.

When using Douglas Crockford's method, you're creating a new object instance that inherits a single existing instance.

When using John Resig's approach, you're creating a constructor function, which you can then use to create instances of the inherited class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.