为什么输出undefined
而不是对象属性。
创建一个函数,定义参数和函数的setter,以输出由参数组成的字符串。
以下是app.js文件的摘要。
// app.js
function Fruit(theColor, sweetness, theName, theOrigin) {
//properties
this.theColor = theColor;
this.sweetness = sweetness;
this.theName = theName;
this.theOrigin = theOrigin;
//functions
this.showName = function () {
console.log("This is a " + this.theName);
};
this.showLand = function () {
this.theOrigin.forEach(function (arg) {
console.log("Grown in: " + arg);
});
};
}
var mango = new Fruit("Yellow", 9, "Mango", ["India", "Central America"]);
console.log(mango.showName() + " " + mango.showLand());

答案 0 :(得分:6)
这一行:
console.log(mango.showName() + " " + mango.showLand());
调用这些函数,然后输出它们的返回值,并在它们之间留一个空格。 showNames
和showLand
都不返回任何内容,因此调用它们会为您提供结果undefined
。
如果您只想调用那些,只需调用它们,而不使用console.log
输出结果。例如,替换:
console.log(mango.showName() + " " + mango.showLand());
与
mango.showName();
mango.showLand();
如果您希望他们返回而不是显示他们的结果,请编辑它们以执行此操作。您必须决定如何showLand
分隔行(例如,使用\n
或通过返回数组等)。
例如,此showName
将返回一个字符串,showLand
将返回一个数组:
//functions
this.showName = function () {
return "This is a " + this.theName;
};
this.showLand = function () {
return this.theOrigin.map(function (arg) {
return "Grown in: " + arg;
});
};
然后你可以像这样调用:
console.log(mango.showName() + ". " + mango.showLand().join(", "));
直播示例:
function Fruit(theColor, sweetness, theName, theOrigin) {
//properties
this.theColor = theColor;
this.sweetness = sweetness;
this.theName = theName;
this.theOrigin = theOrigin;
//functions
this.showName = function () {
return "This is a " + this.theName;
};
this.showLand = function () {
return this.theOrigin.map(function (arg) {
return "Grown in: " + arg;
});
};
}
var mango = new Fruit("Yellow", 9, "Mango", ["India", "Central America"]);
snippet.log(mango.showName() + ". " + mango.showLand().join(", "));

<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
&#13;