什么'我的代码在用对象文字表示法创建方法时出错了

what's wrong with my code in creating a method in object literal notation?

本文关键字:创建 表示 方法 错了 出错 文字 对象 我的 代码 什么      更新时间:2023-09-26

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

这是我的代码。

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行缺少say's that}:bio2:function(){

您的对象应该是这样的,

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工具

您忘记在前一个属性后面放一个逗号,所以它认为它是文本的末尾。也许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);
    }
//   ^
};

您忘记了club: "Fluminense"club: "Zenit St. Petersburg" 之后的,

您在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);
}