Rebol Tutorial
Rebol Tutorial

Reputation: 2754

Extending javascript literal object

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

Answers (3)

Ivo Wetzel
Ivo Wetzel

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

Darin Dimitrov
Darin Dimitrov

Reputation: 1039588

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

JohnDoe.toString = function() {
    return this.firstName + " " + this.lastName;
};

Upvotes: 4

Pointy
Pointy

Reputation: 414086

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

Upvotes: 1

Related Questions