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(o开发者_运维百科ldObject);
versus
newObject = Object.extend();
And I am interested in theories. Implementation wise there does not seem to be much difference.
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.
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.
精彩评论