Home 'this' vs var vs name/value-pair in Objects in JavaScript
Reply: 0

'this' vs var vs name/value-pair in Objects in JavaScript

user806 Published in May 21, 2018, 3:10 am

I'm trying to understand what the difference is in the three versions of code below, specifically:

1) Why is 'this' not of relevance to the object, should it not be used in this context?

2) Why can't I define a var inside this object?

3) Do I have to name/value pairs in objects like this?

If possible, rather than saying 'In JavaScript you do it this way, rather than...', could you please give the reason instead (in simple terms is possible), e.g. 'The reason this line won't work is because...'.


// 1)
var dog = {this.name = "fido" } // SyntaxError: Unexpected token .

// 2)
var dog = { var name = "fido" } // SyntaxError: Invalid shorthand property initializer

// 3)
var dog = { name: "fido" } // All good.
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.31787 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO