如何在reactjs函数对象中进行继承



我如何在Reactjs中进行继承,我正在开发基于画布的应用程序。我需要创建对象,扩展并添加一些东西和事件。例如,我尝试制作基本代码。这是我尝试过的,但没有成功,我想知道我应该做什么来实现这个

export default function car() {
let speed = 40;
let name = 'basic car'
let engine = {
type: petrol
}
this.run = () => {
console.log(name + ' can run with max ' + speed + 'kmph');
}
this.getinfo = () => {
console.log('this is ' + name + ' which can run using ' + engine.type)
}
this.eve = () => {
//Trigger engine object redux events
}
this.getengine = () => {
return engine
}
}
export default mustang extends car() {
this.speed = 200
this.name = 'ford mustang'
this.engine = {
type 'disel'
}
}

let mycar = new mustang()
mycar.run() // Required output = ford mustang can run with max 200kmph
mycar.getinfo() //Required output = this is ford mustang which can run using disel
mycar.eve() // Require output fordcar engine triggler event
mycar.getengine() // Rquire output ford car disel type engine object

您混淆了一些语法。extends关键字只能在使用class语法时使用。它基本上与函数构造函数做同样的事情,但它是ES6中添加的语法糖层,可以更容易地创建对象构造函数。

class Car {
constructor() {
this.speed = 40;
this.name = 'basic car'
this.engine = {
type: 'petrol'
}
}
run() {
console.log(this.name + ' can run with max ' + this.speed + 'kmph');
}
getinfo() {
console.log('this is ' + this.name + ' which can run using ' + this.engine.type)
}
eve() {
//Trigger engine object redux events
}
getEngine() {
return this.engine;
}
}
class Mustang extends Car {
constructor() {
super();
this.speed = 200
this.name = 'ford mustang'
this.engine = {
type: 'diesel'
}
}
}

let mycar = new Mustang()
mycar.run() // Required output = ford mustang can run with max 200kmph
mycar.getinfo() //Required output = this is ford mustang which can run using disel
mycar.eve() // Require output fordcar engine triggler event
mycar.getEngine() // Rquire output ford car disel type engine object

或者使用通过继承原型来扩展函数的经典方法。这基本上与class相同,但需要执行更多步骤。

function Car() {
this.speed = 40;
this.name = 'basic car'
this.engine = {
type: 'petrol'
}
}
Car.prototype.run = function() {
console.log(this.name + ' can run with max ' + this.speed + 'kmph');
}
Car.prototype.getinfo = function() {
console.log('this is ' + this.name + ' which can run using ' + this.engine.type)
}
Car.prototype.eve = function() {
//Trigger engine object redux events
}
Car.prototype.getEngine = function() {
return this.engine
}
function Mustang() {
Car.call(this);
this.speed = 200
this.name = 'ford mustang'
this.engine = {
type: 'diesel'
}
}
Mustang.prototype = Object.create(Car.prototype, {
constructor: {
value: Mustang
}
});
let mycar = new Mustang()
mycar.run() // Required output = ford mustang can run with max 200kmph
mycar.getinfo() //Required output = this is ford mustang which can run using disel
mycar.eve() // Require output fordcar engine triggler event
mycar.getEngine() // Rquire output ford car disel type engine object

最新更新