2

I'm trying to pass this simple test for an assignment and I'm having trouble figuring out how to right the constructor function for it,

describe("Student", function(){
  var student;

  beforeEach(function(){
    student = new Student({firstName: "Lysette", scores: [100, 100, 100, 4, 100]});
  });

  describe("name", function() {
    it("has a first name", function() {
      expect(student.firstName).toEqual("Lysette");
    });
  });

I've tried this, but it doesn't seem to be working:

var Student = function (firstName, scores){
  this.firstName = firstName;
  this.scores = scores;
};

Any Solutions?

Nirav Madariya
  • 1,470
  • 2
  • 24
  • 37

4 Answers4

0

You may use parameter destructuring (ES6):

var Student = function ({firstName, scores}){
  this.firstName = firstName;
  this.scores = scores;
};

Using this,you can just assign firstName and Scores.

Or old, but bulletproof, and assigning all propertys:

var Student = function (changes){
Object.assign( this,changes);
};

So you can do:

new Student({test:true,name:"test"});

Or if you want your original code, you may call it differently:

new Student("Jeff",[0,1,1]);

As youre expecting two parameters in your function...

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • @CarlosG90 actually i think the secons one is the best for you. Please read https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/Destrukturierende_Zuweisung before using the first one... – Jonas Wilms May 24 '17 at 15:27
0

Since functions are first class objects in JavaScript (What is meant by 'first class object'?), they can be passed like objects. This would be similar to how you might use a callback.

function Student(name, functionToBeCalledWhenCreated) // Constructor{
    this.name = name;
    functionToBeCalledWhenCreated(name);
}
function sayStudentsName(name){
    console.log("This student's name is " + name);
}

var glen = new Student("Glen", console.log); //don't include parenthesis on the function or it will call the function
var owen = new Student("Owen", sayStudentsName);
Glen Pierce
  • 4,401
  • 5
  • 31
  • 50
0

You can construct student like this:

function Student(fields){
   this.firstName = fields.firstName;
   .......
} 
Alex Lyalka
  • 1,484
  • 8
  • 13
0

Maybe you can try something like this :

class Student
{
  constructor(firstName, scores) 
  {
    this.firstName = firstName;
    this.scores = scores;
  }
}
var student = new Student('Lysette', [100, 100, 100, 4, 100]);
alert('Name : '+student.firstName+ ' | Scores : '+ student.scores);
Mr972
  • 26
  • 2