【问题标题】:Is it possible to apply two subclasses to one object?是否可以将两个子类应用于一个对象?
【发布时间】: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


【解决方案1】:

你对 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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-08
    • 1970-01-01
    • 1970-01-01
    • 2011-11-29
    • 2011-04-09
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多