JS:驱动程序代码返回false,我不知道为什么?

时间:2014-01-21 19:31:28

标签: javascript

在我开始使用Dev Bootcamp之前,我正在进行练习练习,即使我的驱动程序代码看起来应该是正确的,但它仍然会返回false而不是true。

具体来说,代码

greg.greet()

返回

"Hello, Greg Varias! Glad to have another Island Fox! We'll see you in Summer 2014!"

但是代码

greg.greet() === "Hello, Greg Varias! Glad to have another Island Fox! We'll see you in Summer 2014!";

返回

false

我很抱歉,如果有一个明显的答案,我只是没有看到,但我是新手编程,我已经用尽了我的谷歌搜索能力和其他资源。很感谢任何形式的帮助!

这是我的代码:

function Cohort(cohortName, timeFrame){
  this.name = cohortName;
  this.time = timeFrame;
} 

function Student(studentName, cohortName){
  this.studentName = studentName;
  this.cohortName = cohortName;
  this.greet = greet
}

var greet = function(){
    console.log("Hello, " + this.studentName + "! Glad to have another " + this.cohortName.name + "! We'll see you in " + this.cohortName.time +"!");
}

// driver code

var islandFox = new Cohort("Island Fox", "Summer 2014");
islandFox.name === "Island Fox" //true
islandFox.time === "Summer 2014" //true

var greg = new Student("Greg Varias", islandFox); //undefined 
greg.cohortName.name === "Island Fox" //true
greg.cohortName === islandFox // true

console.log(greg.cohortName) //{ name: 'Island Fox', time: 'Summer 2014' }

greg.greet() === "Hello, Greg Varias! Glad to have another Island Fox! We'll see you in Summer 2014!" //false
greg.greet() //Hello, Greg Varias! Glad to have another Island Fox! We'll see you in Summer 2014!

//第98行的驱动程序代码仍然返回false,即使第99行的greg.greet()似乎完美地打印了确切的短语。 ??

再一次,任何帮助都非常受欢迎,欢迎建设性的批评。我还在学习,如果我继续做错事,我就无法学习。谢谢!

1 个答案:

答案 0 :(得分:4)

因为greet不返回字符串!它什么都不返回

console.log(greg.greet())  //undefined

现在如果功能是

var greet = function(){
    return ("Hello, " + this.studentName + "! Glad to have another " + this.cohortName.name + "! We'll see you in " + this.cohortName.time +"!");
}

你的支票是真的。