Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript object creating

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 javascript array list like this

var students = [];

now i want to push student into students, this is shown below

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

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

here second line occurs exceptions, how can i push javascript object like as c# add list, which is representing second line? thanks

like image 211
Shohel Avatar asked Dec 08 '22 07:12

Shohel


2 Answers

You simply can't, what you can do though is accept a config as a parameter to 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 like this

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

EDIT, PREFERRED ONE

Just as adeneo pointed out if you want to get rid of the repititive || for default values, you can use jQuery to pass them

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;
                };
like image 174
axelduch Avatar answered Dec 22 '22 23:12

axelduch


Make the values that are variable parameters of the function. For example:

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

students.push(new Student(3));

I recommend to read a JavaScript tutorial about functions:

  • MDN - JavaScript Guide
  • Eloquent JavaScript - Functions
  • quirksmode.org - Functions
like image 35
Felix Kling Avatar answered Dec 23 '22 01:12

Felix Kling