【问题标题】:How do I create a class in javascript如何在javascript中创建一个类
【发布时间】:2013-06-11 08:39:55
【问题描述】:

我需要一个 javascript 中的学生类,其中包含 2 个数据成员名称和年龄以及 2 个方法 get_record() 和 set_record(name,age)。如何在 javascript 中执行此操作并创建该类的多个对象。

【问题讨论】:

标签: javascript


【解决方案1】:
var Student  = function(age, name){
  this.age = age;
  this.name = name;

  this.get_age = function(){
      return this.age;
  }
  this.get_name = function(){
      return this.name;
  }
  this.set_age = function(age){
      this.age = age;
  }
  this.set_name = function(name){
      this.name = name;
  }
}

var student = new Student(20,"XYZ");

【讨论】:

    【解决方案2】:

    您可以使用基于 JavaScript 的新语言对类进行建模。 Dart 和 TypeScript 可能是这方面最受欢迎的。

    此示例基于 TypeScript 类的 JavaScript 输出。

        var Student = (function() {
            function Student(name, age) {
                this.name = name;
                this.age = age;
            }
    
            Student.prototype.get_record = function() {
                return "Name: " + this.name + "\nAge: " + this.age;
            }
    
            Student.prototype.set_record = function(name, age) {
                this.name = name;
                this.age = age;
            }
    
            return Student;
        })();
    
    // Usage
    
    var a = new Student("John", 23);
    var b = new Student("Joe", 12);
    var c = new Student("Joan", 44);
    

    【讨论】:

      【解决方案3】:
      function student (age,name) {
              this.name = name;
              this.age = age;
              this.get_record = function() {
                    return "name:"+this.name+" , age:"+this.age;
              }
              this.set_record = function(_name,_age) {
                   this.name=_name;
                   this.age=_age;
              }
          }
      

      【讨论】:

        【解决方案4】:

        您可以使用“构造函数”。

        function Student() {
            this.get_record = function(){ return this.name; };
            this.set_record = function(name, age) { 
                this.name = name; 
                this.age = age; 
            };
        
            return this;
        }
        
        var student1 = new Student();
        var student2 = new Student();
        
        student1.set_record('Mike', 30);
        student2.set_record('Jane', 30);
        
        student1.get_record();
        student2.get_record();
        

        通过原型构造更复杂的类结构

        【讨论】:

          猜你喜欢
          • 2011-03-03
          • 2012-10-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-11-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多