-4

I need a student class in javascript with 2 data members Name and Age and 2 method get_record() and set_record(name,age). How do I do it in javascript and create multiple object of that class.

2

4 Answers 4

4
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");
Sign up to request clarification or add additional context in comments.

Comments

1

You can model classes with new JavaScript based languages. Dart and TypeScript are probably the most popular in this respect.

This example is based on the JavaScript output from a TypeScript class.

    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);

Comments

0
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;
        }
    }

Comments

0

You can use 'constructor function'.

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

More complex class structures are constructed via prototypes

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.