1

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>
1
  • for starters, you want this: JohnDoe.toString = function() { return this.firstName + " " + this.lastName} Commented Nov 22, 2010 at 17:28

3 Answers 3

4

Because you aren't returning anything from this function. Try like this:

JohnDoe.toString = function() {
    return this.firstName + " " + this.lastName;
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks I'm too used to rebol that doesn't need return.
3

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();

3 Comments

uhh ... if he puts a "return" keyword in his "toString" function it'll all work just fine ... when he calls the functions as property references off his "JohnDoe" object, then this will indeed refer to that object
@Pointy yeah, guess I misread the question, guess I'm to tired :/ Reworked it to give some advice on object creation.
Thanks Ivo, I'm not considering prototype yet but I will then I'll look at your sample :)
1

Because you forgot to return the value from the "toString" function you defined.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.