为什么JohnDoe.whoAreYou()确实返回undefined?:
<html>
<head>
</head>
<body>
<script>
var JohnDoe = {
//public property
firstName: "John",
lastName: "Doe",
//public method
whoAreYou: function() {
alert( "I am literal object and my name is " + this.toString());
},
whatIsYourAge: function() {
alert("My age is " + this.Age);
}
};
</script>
<script>
JohnDoe.Age = 10;
JohnDoe.toString = function() {this.firstName + " " + this.lastName};
JohnDoe.whoAreYou();
JohnDoe.whatIsYourAge();
</script>
</body>
</html>
答案 0 :(得分:4)
因为您没有从此功能返回任何内容。试试这样:
JohnDoe.toString = function() {
return this.firstName + " " + this.lastName;
};
答案 1 :(得分:3)
您创建对象的方法非常有限。
您应该从构造函数创建一个新实例,并将值传递给该函数。
function User(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
// set name etc here
}
User.prototype.toString = function() {
// Note the "return" so this function actual returns something
return this.firstName + " " + this.lastName;
}
User.prototype.whoAreYou = function() {
alert( "I am literal object and my name is " + this.toString());
}
var JohnDoe = new User("John", "Doe", 10);
JohnDoe.whoAreYou();
var someoneElse = new User("Someone", "Else", 15);
someoneElse.whoAreYou();
答案 2 :(得分:1)
因为您忘记了return
您定义的“toString”函数的值。