实际上就是clone自己,生成一个新对象。
Object.create() 用到了原型模式的思想。
举例:
//一个原型对象
const myPrototype = {
getName: function () {
console.log(`${this.firstName} ${this.lastName}`);
return `${this.firstName} ${this.lastName}`;
},
say: function () {
console.log('hello');
}
}
//基于原型对象创建实例 x
let x = Object.create(myPrototype);
x.firstName = 'happy';
x.lastName = 'chen';
x.getName();
//基于原型对象创建实例 y
let y = Object.create(myPrototype);
y.firstName = 'hello';
y.lastName = 'world';
y.getName();
// happy chen
// hello world
本文介绍了如何利用JavaScript的Object.create方法实现原型继承,通过创建一个原型对象并使用Object.create基于该原型对象生成新的实例,展示了如何在实例中调用原型上的方法。
2180

被折叠的 条评论
为什么被折叠?



