我试图通过这个简单的测试来完成作业,而我却无法弄清楚如何正确构造函数,
new MainActivity()
我试过这个,但它似乎没有起作用:
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");
});
});
任何解决方案?
答案 0 :(得分:0)
您可以使用参数解构(ES6):
var Student = function ({firstName, scores}){
this.firstName = firstName;
this.scores = scores;
};
使用此功能,您只需指定firstName和Scores。
或旧,但防弹,并分配所有属性:
var Student = function (changes){
Object.assign( this,changes);
};
所以你可以这样做:
new Student({test:true,name:"test"});
或者,如果您需要原始代码,可以采用不同的方式:
new Student("Jeff",[0,1,1]);
正如您期望函数中的两个参数...
答案 1 :(得分:0)
由于函数是JavaScript(What is meant by 'first class object'?)中的第一类对象,因此它们可以像对象一样传递。这与您使用回调的方式类似。
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);
答案 2 :(得分:0)
你可以像这样建立学生:
function Student(fields){
this.firstName = fields.firstName;
.......
}
答案 3 :(得分:0)
也许你可以尝试这样的事情:
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);