我问了一个关于 creating a method in object literal notation 的问题半小时前。我得到了很好的答案,但我的代码仍然有问题。我被告知要创建一个新问题,就在这里。请不要以效率来判断代码。我知道我在每个对象中使用了许多生物方法三次,当时我只能做 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 (){
最佳答案
你的对象应该是这样的,
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 中会中断
您还忘记了函数
之前的逗号
快速提示。调试 javascript 时,错误可能是由上面的行引起的,我建议转到 http://jsfiddle.net并使用内置的 jsHint 工具
关于javascript - 我的代码在以对象文字表示法创建方法时有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17487840/