Creating a javascript object

I have a javascript object like this

 var student = function () {
     this.id = 1;
     this.Name = "Shohel";
     this.Roll = "04115407";
     this.Session = "03-04";
     this.Subject = "CSE";
 };

and I have a list of javascript arrays like this

var students = [];

Now I want to push the student towards the students, as shown below

students.push(new student())  //no prolem

students.push(new student[id = 3]) //Problem

here the second line contains exceptions, how can I click on a javascript object, for example, like a C # add list representing the second line? thank

+4
source share
2 answers

You simply cannot, what you can do, although you accept the configuration as a parameter for your constructor and read it like this:

var student = function (config) {
                config = config || {};
                this.id = config.id || 1;
                this.Name = config.Name || "Shohel";
                this.Roll = config.Roll || "04115407";
                this.Session = config.Session || "03-04";
                this.Subject = config.Subject || "CSE";
            };

And call it that

students.push(new student({id: 3}));

EDIT, PREFERRED ONE

, adeneo , || , jQuery

var student = function (config) {
                    var defaults = {
                        id: 1,
                        Name: "Shohel",
                        Roll: "04115407",
                        Session: "03-04",
                        Subject: "CSE"
                    };
                    config = $.extend(defaults, config || {});
                    this.id = config.id;
                    this.Name = config.Name;
                    this.Roll = config.Roll;
                    this.Session = config.Session;
                    this.Subject = config.Subject;
                };
+8

, . :

var Student = function (id) {
  this.id = id;
  // ...
};

students.push(new Student(3));

JavaScript:

+6

Source: https://habr.com/ru/post/1543810/


All Articles