我想在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
}
}
据我所知,我通常有两种选择以某种方式扩展此类。
A:
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
}
这将缺乏进一步的活动分组。
B:
class Student extends Person {
// do whatever a student does
}
class FootballPlayer extends Person {
// do whatever a footballPlayer does
}
该选项将无法为一个人分配多个活动。
是否有一种方法可以为某个对象创建尽可能多的子类?
我现在已经将闭包拆分为多个文件,并根据我需要的“活动”将它们放到服务器上。 但是我不喜欢这种解决方案。
预先感谢
安德烈
答案 0 :(得分:0)
您对javascript类的理解不佳
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
this.WhatFor = {};
}
WhatIsFor(){
console.log('WhatFor', this.WhatFor);
}
}
class Student extends Person {
study(subject) {
this.WhatFor.subject = subject;
console.log (this.name,this.age, 'study');
}
driveToUniversaty(UniversatyName) {
this.WhatFor['UniversatyName'] = UniversatyName;
console.log (this.name,this.age, 'driveToUniversaty');
}
}
class FootballPlayer extends Person {
constructor(name, age, footballClub) {
super(name, age);
this.footballClub = footballClub;
}
playFootball() {
console.log (this.name,this.age, 'playFootball');
}
driveToFootballTraining() {
console.log (this.name,this.age, 'driveToFootballTraining');
}
}
var Paul = new Student('Paul',24);
var John = new FootballPlayer('John',12, 'unbeatable lions' );
Paul.study('computer science');
Paul.WhatIsFor();