0

半小时前,我问了一个关于用对象文字表示法创建方法的问题。我得到了很好的答案,但我的代码仍然有问题。我被告知要创建一个新问题,就在这里。请不要以效率来判断代码。我知道我在每个对象中使用了很多 bio 方法 3 次,当时我可以做 1 个函数,但我这样做是为了更多地了解对象、函数和方法。

所以这是我的代码。

var object1 = new Object()
object1.name = "Neymar";
object1.age = 22;
object1.club = "Barca";
object1.bio = function (){
    console.log(this.name +" is "+ this.age + " years old and he is playing in "+ this.club);
};
var object2 = {
name: "Fred",
age: 28,
club: "Fluminense"
bio2: function (){
    console.log(this.name +" is "+ this.age + " years old and he is playing in "+ this.club);
    };
};
var object3 = {
name: "Hulk",
age: 27,
club: "Zenit St. Petersburg"
bio3: function (){
    console.log(this.name +" is "+ this.age + " years old and he is playing in "+ this.club);
    };
};
object1.bio();
object2.bio2();
object3.bio3();

CodeAcademy 说第 12 行缺少 }: bio2: function (){

4

4 回答 4

2

您忘记在前一个属性之后放置逗号,因此它认为它是文字的结尾。也许expected ',' or '}'会是一个更好的消息。此外,在对象文字内,您不允许放置行分隔符(分号)。它应该是

var object2 = {
    name: "Fred",
    age: 28,
    club: "Fluminense",
//                    ^
    bio2: function() {
        console.log(this.name +" is "+ this.age + " years old and he is playing in "+ this.club);
    }
//   ^
};
var object3 = {
    name: "Hulk",
    age: 27,
    club: "Zenit St. Petersburg",
//                              ^
    bio3: function() {
        console.log(this.name +" is "+ this.age + " years old and he is playing in "+ this.club);
    }
//   ^
};
于 2013-07-05T11:29:52.313 回答
2

你忘记,club: "Fluminense"club: "Zenit St. Petersburg"

于 2013-07-05T11:30:21.510 回答
2

你的对象应该是这样的,

var object2 = {
   name: "Fred",
   age: 28,
   club: "Fluminense",
   bio2: function (){
      console.log(this.name +" is "+ this.age + " years old and he is playing in "+ this.club);
   }
};

您在 js 对象中永远不会有分号-无论如何您都有分号,并且您也不应该在对象的最后一项上使用逗号-它在 IE 中中断

你也忘记了前面的逗号function

小建议。在调试 javascript 时,错误可能是由上面的行引起的,我建议转到http://jsfiddle.net并使用内置的 jsHint 工具

于 2013-07-05T11:31:17.910 回答
1

您在和之后遗漏了一个常见的 ( ,) 。您还必须从对象参数的末尾删除行尾分隔符 ( )。club: "Fluminense"club: "Zenit St. Petersburg";

var object2 = {
    name: "Fred",
    age: 28,
    club: "Fluminense",
    bio2: function (){
    console.log(this.name +" is "+ this.age + " years old and he is playing in "+ this.club);
}

};
var object3 = {
    name: "Hulk",
    age: 27,
    club: "Zenit St. Petersburg",
    bio3: function (){
    console.log(this.name +" is "+ this.age + " years old and he is playing in "+ this.club);
}
于 2013-07-05T11:34:13.127 回答