javascript - 使用 Object.create 创建的对象会继承原型(prototype)吗?

标签 javascript inheritance

考虑以下代码:

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/

相关文章:

php - Google map javascript api 无法从 mysql 数据库加载标记

javascript - 以 CommonJS View 方式导入 fullPage.js

javascript - Node.js 使用父对象的数据填充子对象(使用 util.inherits 进行继承)

java - 不能在运行时在 Java 中向下转换

继承属性类的 c# OO 建议

javascript - 在 Rails 博客确认删除消息中包含 <%= post.title %>

javascript - Div 包括另外两个总计大于父 div 的 div。需要显示更多的第一个 div 内容。

javascript - 你能用 Javascript 更新 meta 和 Open Graph 标签吗?

c++ - 基类声明虚函数,其参数类型取决于实现类

c++ - 在 C++ 多重继承中如何选择将继承哪个基类方法?