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

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...'.

Thanks:)

// 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.

1 answer

  • answered 2018-04-14 15:49 Crazy Train

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

    Because this is basically an automatic identifier that is bound to functions (but not "arrow functions") or the global scope. There's simply no relationship between it and object literal syntax.

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

    Because the var syntax in JS is used exclusively for local variables, and not for object properties. The language designers decided to make the syntax entirely distinct.

    This creates an easy, visual distinction between a local variable and an object property.

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

    There are other syntax possibilities, but generally yes, to define an object using an object literal initializer, you use key/value pairs.