Reputation: 3
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
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
.
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