类对象与构造函数间原型链构建报错:为何Object.create赋值失败?
类的prototype无法直接赋值,构造函数却可以?原因和解决方法
核心原因:ES6类的prototype是只读属性
ES6类语法不是简单的构造函数语法糖——它对prototype属性做了严格限制:类的prototype被设置为不可写(writable: false)。所以你直接给EV.prototype赋值Object.create(Car.prototype)时,会触发只读属性的错误。
而普通构造函数(比如你的Car)的prototype是一个普通可写对象,没有这个限制,自然可以直接替换来构建原型链。
正确实现原型链关联的方法
推荐:用ES6类的extends语法
这是类继承的标准写法,底层会自动帮你处理原型链,还能正常使用super调用父构造函数:
const Car = function (make, speed) { this.make = make; this.speed = speed; }; Car.prototype.accelerate = function () { this.speed += 10; console.log(`${this.make} 当前速度:${this.speed}`); }; class EV extends Car { constructor(make, speed, charge) { // 必须先调用super初始化父类逻辑,才能使用this super(make, speed); this.charge = charge; } } // 测试 const tesla = new EV('特斯拉', 120, 23); tesla.accelerate(); // 输出:特斯拉 当前速度:130 console.log(Object.getPrototypeOf(EV.prototype) === Car.prototype); // true,原型链关联成功
手动修改原型链(仅作理解,不推荐)
如果一定要手动关联,不能替换EV.prototype,而是要修改它的原型指向:
const Car = function (make, speed) { this.make = make; this.speed = speed; }; Car.prototype.accelerate = function () { this.speed += 10; console.log(`${this.make} 当前速度:${this.speed}`); }; const EV = class { constructor(make, speed, charge) { Car.call(this, make, speed); this.charge = charge; } }; // 修改EV.prototype的原型为Car.prototype Object.setPrototypeOf(EV.prototype, Car.prototype); // 测试 const tesla = new EV('特斯拉', 120, 23); tesla.accelerate(); // 输出:特斯拉 当前速度:130 console.log(Object.getPrototypeOf(EV.prototype) === Car.prototype); // true
这种方式虽然能实现需求,但不符合ES6类的设计规范,而且无法使用super,所以尽量用extends。
内容的提问来源于stack exchange,提问作者Parhamhri
相关产品推荐
相关产品推荐

