它无法正常工作,它输出未定义
It's not working correctly, it outputs undefined?
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
相关文章:
- Node.js/Express未输出console.log,highcharts.js给出未定义的错误
- JS函数只返回未定义的数据,但alert输出正确的数据
- '未定义'当需要模块时输出
- 具有中文字符但输出的JSON.parse数据变为“;未定义”;
- 为什么我的输出未定义
- IE9中的有效输出,但IE7/IE8中的未定义输出
- 当在 Javascript 中使用许多 for 循环时,输出是未定义的
- 它无法正常工作,它输出未定义
- Vue.js 使用 Vuex 和自定义组件,@click方法输出未定义
- 带有Ajax的JavaScript和HTTP请求输出未定义的显示2
- 对象实例为其输出“未定义”'s原型'的属性.为什么?
- 输出未定义
- FileReader输出未定义
- 使用数组.Push输出未定义
- 从函数调用返回对象的函数输出未定义
- js部分/子模板输出未定义
- Angular UI掩码格式化输出未定义
- jsPdf输出未定义
- 对变量的访问输出未定义
- 为什么输出未定义