Object.create()和__proto__实现继承对新增对象的影响

本文探讨了JavaScript中两种实现继承的方法:Object.create()和__proto__。通过实例展示了它们如何影响对象的原型链,以及在添加新方法时的不同行为。使用Object.create()后,原型对象被改变,导致实例无法访问新增的eat方法。而使用__proto__则成功改变了原型对象的父级引用,使得实例能够正确调用新增方法。
摘要由CSDN通过智能技术生成

__proto__和Object.create()实现继承对新增对象的影响

先创建实例对象,在使用Object.create和__proto__改变对象的原型,来实现继承,会存在不同的结果
1.使用Object.create

function User() {}
User.prototype.name = function() {
	console.log("user.name")
}
function ChildFirst() {}
let childFirst = new ChildFirst(); // 实例化对象
ChildFirst.prototype = Object.create(User.prototype) //实现继承
ChildFirst.prototype.eat = function() {
	console.log("child.eat")
}
childFirst.eat(); // 报错:找不到eat方法

2.使用__proto__

function User() {}
User.prototype.name = function() {
	console.log("user.name")
}
function ChildFirst() {}
let childFirst = new ChildFirst(); // 实例化对象
ChildFirst.__proto__ = User.prototype //实现继承
ChildFirst.prototype.eat = function() {
	console.log("child.eat")
}
childFirst.eat(); // child.eat

通过上述使用的案例发现:
1.Object.create使用后改变了原型对象
2.__proto__使用后改变原型对象父级的指向

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值