为什么JavaScript原型继承中类的方法与属性表现不同?
JavaScript原型继承中属性与方法查找差异的原因
先看你的代码:
class childX { vehicleType = "Not Available"; methX(){ console.log("Hello from the ChildX object"); } } class ParentX { vehicleType = "Truck"; methX(){ console.log("Hello from the ParentX object"); } } let childObj = new childX(); let parentObj = new ParentX(); childObj.__proto__ = parentObj; console.log("Child Vehicle Type: ", childObj.vehicleType);// output: Not Available childObj.methX(); // output: Hello from the ParentX object
为什么属性和方法的表现不一样?
类字段是实例自身属性:你在
childX和ParentX里用vehicleType = "xxx"定义的是实例属性,不是原型属性。当创建childObj时,childX的vehicleType已经被直接添加到childObj这个实例上了。哪怕后续把childObj的原型改成parentObj,访问childObj.vehicleType时,JS会优先取实例自己身上的属性,不会去原型链找parentObj的vehicleType。类方法存放在原型对象上:类里定义的
methX()方法,是挂载到类的原型对象(比如childX.prototype、ParentX.prototype)上的。childObj实例本身并没有methX属性,调用时会顺着原型链查找。当你把childObj.__proto__改成parentObj后,原型链变成了childObj → parentObj → ParentX.prototype → Object.prototype,原来的childX.prototype被跳过,最终找到的是ParentX.prototype上的methX方法,所以输出父类的内容。
额外提醒
直接修改__proto__性能较差,推荐用Object.setPrototypeOf(childObj, parentObj)来修改实例原型。另外ES6类继承更推荐用extends关键字,它能正确设置原型链并处理继承细节,比如:
class childX extends ParentX { vehicleType = "Not Available"; methX(){ console.log("Hello from the ChildX object"); } }
内容的提问来源于stack exchange,提问作者nilesh unde
相关产品推荐
相关产品推荐

