Peter F. Wagner
Peter F. Wagner

Reputation: 3

Will object created with Object.create inherit from the prototype?

Consider the following code:

var oNew = Object.create(MyConstructor.prototype);

Say, MyConstructor has "own" data members defined inside the constructor. Will oNew inherit those data members? Will oNew inherit all the MyConstructor.prototype methods? Also, MyConstructor.prototype may itself in inherit from an object, say new f().

Upvotes: 0

Views: 44

Answers (1)

gyre
gyre

Reputation: 16779

Say, MyConstructor has "own" data members defined inside the constructor. Will oNew inherit those data members?

No, it will not; the prototype's constructor function is separate from the prototype intentionally. One of the main benefits of Object.create is that it allows you to separate the process of object creation from that of object instantiation (calling a constructor using new does combines the two).

Will oNew inherit all the MyConstructor.prototype methods?

Yes, properties assigned directly to the prototype are inherited even when using Object.create.

Demo

function MyConstructor () {
  this.ownProperty = 'value'
}

MyConstructor.prototype.inheritedProperty = 'value'

var createdObject = Object.create(MyConstructor.prototype)

console.log(createdObject)
console.log('inheritedProperty' in createdObject) //=> true
console.log('ownProperty' in createdObject) //=> false


var constructedObject = new MyConstructor()

console.log(constructedObject)
console.log('inheritedProperty' in constructedObject) //=> true
console.log('ownProperty' in constructedObject) //=> true

Upvotes: 1

Related Questions