2017-05-24 76 views
2

我想通过这个简单的测试赋值和我有麻烦搞清楚如何适合它的构造函数,如何使一个在Javascript中使用函数的对象构造函数?

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

我已经试过这一点,但它似乎没有要工作:

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

任何解决方案?

+0

什么哟由意味着“似乎并不奏效”? –

+3

您正在传递包含两个属性“firstName”和“scores”的对象,而不是两个单独的参数。你想要哪些行为? –

+0

这与构造函数的功能有什么关系? – Bergi

回答

0

您可以使用参数解构(ES6):

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

利用这一点,你可以指定firstName和成绩。

还是老的,但防弹,并指派了所有propertys:

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

所以,你可以这样做:

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

或者,如果你希望你的原代码,你可能有不同的称呼它:

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

由于您期望两个参数在你的函数中...

+1

我知道这是正确的,但我觉得我们在作弊...... – evolutionxbox

+1

第一个对我最有意义,谢谢! – CarlosG90

+0

@ CarlosG90其实我认为secons one是最适合你的。请在使用第一个之前阅读https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/Destrukturierende_Zuweisung ... –

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

您需要使用'new'关键字:var glen = new Student(“格伦“,console.log) –

+0

谢谢余下。 –

0

您可以构建学生是这样的:

function Student(fields){ 
    this.firstName = fields.firstName; 
    ....... 
} 
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); 
+0

这只是OP所做的语法糖。 – 4castle

相关问题