它无法正常工作,它输出未定义

It's not working correctly, it outputs undefined?

本文关键字:输出 未定义 工作 常工作      更新时间:2023-09-26
function Rabbit(adjective) {
    this.adjective = adjective;
    this.describeMyself = function() {
        console.log("I am a " + this.adjective + " rabbit");
    };
}
// now we can easily make all of our rabbits
rabbit1 = new Rabbit("fluffy");
rabbit2 = new Rabbit("happy");
rabbit3 = new Rabbit("sleepy");
console.log(rabbit1.describeMyself());
console.log(rabbit2.describeMyself());
console.log(rabbit3.describeMyself());

输出:

I am a fluffy rabbit
undefined
I am a happy rabbit
undefined
I am a sleepy rabbit
undefined

如果我将其作为.js文件而不是控制台执行,它会停止未定义吗?还是一样?

您正在尝试控制台.log一个不会返回任何内容的函数,因此结果显示为未定义。您只需调用该函数,因为您已经在其中.log控制台。试试这个

rabbit1.describeMyself(); rabbit2.describeMyself(); rabbit3.describeMyself();

describeMyself() 不显式返回任何内容,因此它为每个console.log(rabbit1.describeMyself())隐式返回undefined

你的代码等效于这个

function Rabbit(adjective) {
    this.adjective = adjective;
    this.describeMyself = function() {
        console.log("I am a " + this.adjective + " rabbit");
        return undefined; // <-- without a return statement, undefined will be returned.
    };
}
// now we can easily make all of our rabbits
rabbit1 = new Rabbit("fluffy");
var result = rabbit1.describeMyself(); // <-- the message logged to console and return undefined
console.log(result); // and print undefined again

所以解决方案是从方法返回字符串


function Rabbit(adjective) {
    this.adjective = adjective;
    this.describeMyself = function() {
        return "I am a " + this.adjective + " rabbit"); // <-- return a string
    };
}
// now we can easily make all of our rabbits
rabbit1 = new Rabbit("fluffy");
console.log(rabbit1.describeMyself()); // <-- log the string value

或删除额外的日志

function Rabbit(adjective) {
    this.adjective = adjective;
    this.describeMyself = function() {
        console.log("I am a " + this.adjective + " rabbit");
    };
}
// now we can easily make all of our rabbits
rabbit1 = new Rabbit("fluffy");
rabbit1.describeMyself(); // <-- this method will print to console and return undefined