Jitender
Jitender

Reputation: 7971

inherit from prototype vs inherit from constructor

I was searching about more for Object.create. I have found a this question already asked by users. In accepted answer they are talking about inheritance like

Object.create builds an object that inherits directly from the one passed as its first argument.

var o = new SomeConstructor();

In the above example, o inherits directly from SomeConstructor.prototype

Now I just want to know what is the mean of inherits from prototype and how it make difference practically from inherit directly from constructor

Upvotes: 1

Views: 58

Answers (1)

wmock
wmock

Reputation: 5492

Explanation of Object.create

When you do something like this:

var obj = Object.create( baseMethods );

obj.ownMethod = function () {
  console.log( 'baz' );
};

var baseMethods = {
  method1: function () {
    console.log( 'something' );
  },
  method2: function () {
    console.log( 'foobar' );
  }
};

The object obj delegates to the baseMethod object whenever the JavaScript engine can't find a property on obj. For example, if you invoke:

obj.method1(); // will log 'something'

The JavaScript engine will first try to look up the property on obj. Since the property can't be found on obj, it will delegate the lookup to its prototype object (which we've defined using Object.create). In this case, the prototype object is baseMethod. Now that the property has been found, the engine will execute method1.

Explanation of Constructor.prototype

In your code, you have:

var o = new SomeConstructor();

Think of SomeConstructor as having an object similar to my baseMethods object where instances of SomeConstructor will first look up properties on the instance itself and then delegate to that object if the property can't be found. In your example, it just so happens that the object that instances of SomeConstructor will delegate to is SomeConstructor.prototype.

Looking at your question, please don't make the mistake of thinking that o inherits from SomeConstructor - the correct way to think of it is that o delegates its object-lookup to an object which just so happens to be a property on the SomeConstructor function object (namely, SomeConstructor.prototype)

Upvotes: 1

Related Questions