【发布时间】:2019-05-13 13:45:37
【问题描述】:
我想在 JavaScript 中创建一个类,然后由多个子类扩展。
我能够为我需要的东西创建一个闭包,但由于代码越来越多,拥有一个巨大的文件变得令人困惑。
假设我有一个人。
一个人可以是学生、足球运动员、...
但一个人也可以是学生和足球运动员。
我有一个可以代表这个的工作闭包:
var jack = (
function() {
var name = jack;
var age = 24;
return {
student: function() {
var subject = 'computer science'
return {
driveToUniversaty: function() {
// drive for a while...
},
study: function() {
// read books and stuff...
},
}
},
footballPlayer: function() {
var footballClub = 'unbeatable lions'
return {
driveToFootballTraining: function() {
// drive for a while in a different direction...
},
playFootball: function() {
// kick a ball with the guys
},
}
},
}
}
)();
我现在尝试使用 js 类来实现这一点。这是基础:
class Person {
constructor(name, age) {
this.name = name
this.age = age
}
}
据我所知,我通常有两种选择以某种方式扩展此类。
答:
Person.prototype.driveToUniversaty = function() {
// drive for a while...
}
Person.prototype.study = function() {
// read books and stuff...
}
Person.prototype.driveToFootballTraining = function() {
// drive for a while in a different direction...
}
Person.prototype.playFootball = function() {
// kick a ball with the guys
}
这将缺少对活动的进一步分组。
乙:
class Student extends Person {
// do whatever a student does
}
class FootballPlayer extends Person {
// do whatever a footballPlayer does
}
该选项无法将多个活动分配给一个人。
有没有办法为某个对象创建任意数量的子类?
我现在已经将闭包拆分为多个文件,并根据我需要的“活动”将它们放在服务器上。 但我不喜欢这种解决方案。
提前致谢
安德烈
【问题讨论】:
标签: javascript class closures