const person = {
isHuman: false,
printIntroduction: function() {
console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
}
};
const me = Object.create(person);
me.name = 'Matthew'; // “name”是设置在“me”上的属性,而不是“person”上
me.isHuman = true; // 可以覆盖继承的属性
me.printIntroduction();
// "My name is Matthew. Am I human? true"
用法
Object.create(proto)
proto 新创建对象的原型对象。
返回一个新对象,带着指定的原型对象及其属性。
proto 参数需为 null 或 除基本类型包装对象以外的 对象。如果 proto 不是这几类值,则抛出一个 TypeError 异常。
本系列的主题是 JavaScript 深入系列,每期讲解一个技术要点。如果你还不了解各系列内容,文末点击查看全部文章,点我跳转到文末。
如果觉得本系列不错,欢迎 Star,你的支持是我创作分享的最大动力。
Object.create 的模拟实现
Object.create()
方法用于创建一个新对象,使用现有的对象来作为新创建对象的原型(prototype)。用法
proto
新创建对象的原型对象。返回一个新对象,带着指定的原型对象及其属性。
proto
参数需为null
或 除基本类型包装对象以外的对象
。如果proto
不是这几类值,则抛出一个TypeError
异常。用 Object.create() 实现类式继承
下面的例子演示了如何使用
Object.create()
来实现类式继承。这是一个所有版本 JavaScript 都支持的单继承。实现
思路:创建一个空的构造函数,将传入的对象作为这个构造函数的原型(prototype),最后返回构造函数的实例对象。
参考这篇 https://www.cnblogs.com/ranyonsue/p/11201730.html 博客,里面一种 JS 实现继承的方式用到的就是上面的实现方式,其实就是手写了一个
Object.create
方法,来实现了继承。查看全部文章
博文系列目录
交流
各系列文章汇总:https://github.com/yuanyuanbyte/Blog
我是圆圆,一名深耕于前端开发的攻城狮。