gpt4 book ai didi

javascript - Javascript 继承链中的“this”关键字

转载 作者:行者123 更新时间:2023-11-30 14:18:30 25 4
gpt4 key购买 nike

我有一个名为 Car 的函数作为父类(super class)型

let Car = function(){};
Car.prototype = {
constructor: Car,
numWheel: 4,
numLight : 2,
describe = function () {
console.log(`This car is ${this.name} produced in ${this.version} `);
}
}

我想让一个子类型构造函数继承自它,并从这个构造函数创建一个实例

let Honda = function (name, version) {
this.name = name;
this.version = version;
}
Honda.prototype = Object.create(Car.prototype);
Honda.prototype = {
constructor: Honda
}
let civic = new Honda('civic', 2015);

我想提出的问题是父类(super class)型中的“this”在此处的子类型对象中指向何处。当我尝试调用函数时

civic.describe;

出现错误。

Uncaught SyntaxError: Invalid shorthand property initializer

为什么不能继承'this'关键字?

最佳答案

您的代码有几个问题:

  1. 您将函数分配给对象属性的方式 (describe = function() {/* ... */}) 在语法上是无效的。
  2. 您重新分配给 Honda 原型(prototype),覆盖您之前使用 Object.create() 分配的内容。

此代码段通过正确初始化对象和使用 Object.assign 解决了这两个问题。 :

let Car = function() {};
Car.prototype = {
constructor: Car,
numWheel: 4,
numLight: 2,
describe: function() {
console.log(`This car is ${this.name} produced in ${this.version} `);
}
}


let Honda = function(name, version) {
this.name = name;
this.version = version;
}
Honda.prototype = Object.assign({}, Car.prototype, {
constructor: Honda
});

let civic = new Honda('civic', 2015);
civic.describe();

关于javascript - Javascript 继承链中的“this”关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53148957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com