手写实现 Object.create
关键词:Object.create 实现、Object.create 手写
Object.create() 方法可以用于创建一个新对象,使其原型与指定的对象完全相同。可以通过以下方式手写实现 Object.create() 方法。
function createObject(proto) { function F() {} F.prototype = proto; return new F(); } // Example usage const person = { firstName: 'John', lastName: 'Doe', fullName: function() { return this.firstName + ' ' + this.lastName; } }; const anotherPerson = createObject(person); anotherPerson.firstName = 'Jane'; console.log(anotherPerson.fullName()); // Output: "Jane Doe"
该实现方式创建了一个名为 F 的空函数,将其原型设置为传入的 proto 对象,然后返回一个新创建的 F 函数对象。这个新对象的原型与传入的 proto 对象相同,从而实现了 Object.create() 的功能。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论