【发布时间】:2017-02-04 21:47:39
【问题描述】:
我想在我的对象中添加以下方法:
" hello - 此方法将字符串 "Hello, my name is" 记录到控制台 后面是演员的名字。 "
有人能帮我找出这段代码的错误吗? :
function Person (firstName, lastName, age, numOscars) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.numOscars = numOscars;
hello : function greeting() {
console.log ("Hello, my name is " + this.firstName);
}
}
var actors = new Array ();
actors[0] = new Person ("Leonardo", "DiCaprio", 41, 1);
actors[1] = new Person ("Jennifer", "Lawrence", 25, 1);
actors[2] = new Person ("Samuel L."," Jackson", 67, false);
actors[3] = new Person ("Meryl", "Streep", 66, 3);
actors[4] = new Person ("John", "Cho", 43, false);
Person.hello();
提前非常感谢您;)
【问题讨论】:
-
旁白:“你得了多少奥斯卡奖?” – “假” – 看起来像一个奇怪的值。如果你没有奥斯卡奖,奥斯卡奖数是
0,而不是false。 -
您在将 fn
greeting分配给hello时混淆了函数体语法和对象方法声明。您只需将该 fn 分配给构造函数中的this.hello属性,就像您对firstName、lastName和其他属性所做的那样
标签: javascript arrays object methods