当我在console.log时,这段代码:
var Student = function(name, address, gpa){
console.log(this);
this.name = name;
this.address = address;
this.gpa = gpa;
console.log("name is equal to " + name);
console.log("address is equal to " + address);
console.log("gpa is equal to " + gpa);
};
var studentCall = [
new Student ({
name: "Marshae Hannor",
address:{
street: "345 Main St",
city: "Smyrna",
state: "GA"},
gpa: [2.5, 3.5, 4.0]}),
new Student ({
name: "Vernon Owens",
address:{
street: "439 Serious St",
city: "Baltimore",
state: "MD"},
gpa: [3.5, 3.2, 3.7]})
];
这是我在console.log中获得的内容
Object {} main2.js (line 39) name is equal to [object Object] main2.js (line 44) address is equal to undefined main2.js (line 45) gpa is equal to undefined main2.js (line 46) Object {} main2.js (line 39) name is equal to [object Object] main2.js (line 44) address is equal to undefined main2.js (line 45) gpa is equal to undefined
有人可以帮我理解我做错了什么。感谢
答案 0 :(得分:2)
在您对Student
的调用中,您传递了一个单参数,该参数如下所示:
{
name: "Marshae Hannor",
address:{
street: "345 Main St",
city: "Smyrna",
state: "GA"},
gpa: [2.5, 3.5, 4.0]
}
但是你的Student
函数希望得到三个离散的参数。所以你不用{
和}
来调用它而不给出参数的名称:
var studentCall = [
new Student (
"Marshae Hannor",
{
street: "345 Main St",
city: "Smyrna",
state: "GA"},
[2.5, 3.5, 4.0]),
new Student (
"Vernon Owens",
{
street: "439 Serious St",
city: "Baltimore",
state: "MD"},
[3.5, 3.2, 3.7])
];
或,修改Student
以期望只接收包含这些属性的单个对象:
var Student = function(obj){
console.log(this);
this.name = obj.name;
this.address = obj.address;
this.gpa = obj.gpa;
console.log("name is equal to " + this.name);
console.log("address is equal to " + this.address);
console.log("gpa is equal to " + this.gpa);
};