Reputation: 2754
Why JohnDoe.whoAreYou() does return 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>
Upvotes: 1
Views: 1059
Reputation: 46756
Your approach to creating objects is very limiting.
You should rather create a new instance from a constructor and pass in the values to that function.
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();
Upvotes: 3
Reputation: 1039588
Because you aren't returning anything from this function. Try like this:
JohnDoe.toString = function() {
return this.firstName + " " + this.lastName;
};
Upvotes: 4
Reputation: 414086
Because you forgot to return
the value from the "toString" function you defined.
Upvotes: 1