我有一个名为Car的函数作为超类型
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);
我要提出的问题是超类型中的“ this”在此处指向子类型对象的位置。当我尝试调用该函数
civic.describe;
出现错误。
未捕获到的SyntaxError:速记属性初始化程序无效
为什么'this'关键字不能被继承?
答案 0 :(得分:2)
您的代码有两个问题:
describe = function() { /* ... */}
)的方法在语法上是无效的。Honda
原型,覆盖先前使用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();