考虑以下代码:
var oNew = Object.create(MyConstructor.prototype);
假设,MyConstructor
在构造函数内定义了“自己的”数据成员。 oNew
会继承这些数据成员吗? oNew
会继承所有 MyConstructor.prototype
方法吗?另外,MyConstructor.prototype
本身可以从一个对象继承,例如 new f()
。
最佳答案
Say,
MyConstructor
has "own" data members defined inside the constructor. Will oNew inherit those data members?
不,不会;原型(prototype)的构造函数有意与原型(prototype)分离。 Object.create
的主要好处之一是,它允许您将对象创建的过程与对象实例化的过程分开(调用使用 new
的构造函数确实结合了两者)。
Will oNew inherit all the
MyConstructor.prototype
methods?
是的,即使使用Object.create
,直接分配给原型(prototype)的属性也会被继承。
演示
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
关于javascript - 使用 Object.create 创建的对象会继承原型(prototype)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42522758/