joni
joni

Reputation: 41

One object , two methods

I try to understand why this works

// .......................................................

var hero = { 
  name: 'Joni', 
  type: 'blond',
  sayName: function() { 
    return this.name; 
  } 

  sayType: function() { 
    return this.type; } 
} 
document.write( hero.sayName()+ "</br>"); 
document.write( hero.sayType());

// .......................................................

but this doesn't works

// .......................................................

var hero = { 
  name: 'Joni', 
  type: 'blond',
  sayName: function() { 
    return this.name; 
  } 

  sayType: function() { 
    return this.type; 
    } 
} 
document.write( hero.sayName()+ "</br>"); 
document.write( hero.sayType());

// .......................................................

thanks

Upvotes: 0

Views: 136

Answers (3)

aiham
aiham

Reputation: 3614

You are missing a comma after the sayName function. I couldn't see a difference between the two blocks of code, other than a new line character (Which doesn't make a difference). Both blocks of code were missing this comma.

var hero = { 
  name: 'Joni', 
  type: 'blond',
  sayName: function() { 
    return this.name; 
  },// <---  Missing Comma

  sayType: function() { 
    return this.type; 
    } 
} 
document.write( hero.sayName()+ "</br>"); 
document.write( hero.sayType());

Upvotes: 0

refro
refro

Reputation: 209

The difference is in the enter before the saytype function in the second block. Besides the comma i see no reason why it wouldn't work.

Upvotes: 0

selbie
selbie

Reputation: 104579

You are missing a semi-colon at the end of the "var hero" statement. You are also missing some other commas.

var hero = { 
  name: 'Joni', 
  type: 'blond',
  sayName: function() { 
    return this.name; 
  }, // <<--- You missed the comma here

  sayType: function() { 
    return this.type; 
    } 
};  // <<--- You missed the semi colon!
document.write( hero.sayName()+ "</br>"); 
document.write( hero.sayType());

Going forward, you can completely avoid these issues by just running your code through JSLINT. Goto jslint.com, paste your code, and you'll see the answers revealed to you.//

Upvotes: 1

Related Questions