它运行不正常,输出undefined?

时间:2016-03-14 03:23:32

标签: javascript

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文件而不是控制台执行,它会停止undefined吗?或者会是一样的吗?

3 个答案:

答案 0 :(得分:1)

你正在尝试console.log一个什么都不返回的函数,所以结果显示为undefined。你需要调用该函数,因为你已经有了console.log。试试这个

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

答案 1 :(得分:0)

describeMyself()并未明确返回任何内容,因此会隐式返回undefined console.log(rabbit1.describeMyself())

答案 2 :(得分:0)

您的代码等同于此

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