-1

For example, I have code like this:

var Player = function(param){
    var self = {
    x:0,
    y:0,
    spdX:0,
    spdY:0,
    id:"",
    }
    self.hp = 24;
}

Do I need to add hp inside var self = {}?

leonylyner
  • 117
  • 2
  • 7
  • 1
    No...what you are doing is standard practice. You can add properties after an object has been declared just the way you are doing – charlietfl Nov 18 '17 at 01:55
  • The only issue is that it can become cumbersome to keep track of what properties and object has if you define them all over your code. But that's a problem for humans reading the code — javascript won't complain. – Mark Nov 18 '17 at 01:57
  • Your question is incorrect. That property is `declared` when you populate it. This is how it's done. You do it whenever you want to add a property to an object that has already been defined. You don't use `var` for object properties. – tao Nov 18 '17 at 01:59
  • **No**. That's the answer to your question. – Chris Happy Nov 18 '17 at 02:05
  • 1
    That's not a variable. Properties cannot be declared in JavaScript. – Bergi Nov 18 '17 at 02:16
  • Just a note, you have called your variable `self`, people might think your referring to object properties naming something like that, in fact what you have created is a locally scoped variable called `self` inside you constructor. Instead for object properties you want `this`, eg.. `this.x = 0` etc. – Keith Nov 18 '17 at 02:21
  • @Keith that is not always the case if you aren't using `new` – charlietfl Nov 18 '17 at 02:23

2 Answers2

1

I believe others have misunderstood the question. If I understand correctly, you are asking about any potential issues with dynamically adding properties to an existing object (vs. when first declaring the object). The answer is that it is fine to do, is common JS practice and should have no negative performance impact.

This is a perfectly reasonable question if you are coming from a statically typed language background. For example, in TypeScript, you cannot add properties to an object after it has been defined (see this question). This is done for:

  1. Type safety (far and away the main reason)

  2. Performance (possibly).

davidchappy
  • 281
  • 1
  • 8
  • But question isn't about typeScript. – charlietfl Nov 18 '17 at 02:03
  • 1
    @charlietfl I clarified the first part of my answer a bit. However, my intention is simply to affirm the validity of the question using TypeScript as an example, which happens to be a superset of JavaScript. – davidchappy Nov 18 '17 at 02:10
1

No

It's completely alright. Relax. Your code isn't going to explode. Breathe. Breathe! Okay, now that you're settled down...

Performance wise, it's the same*: Performance test.

Syntax wise, they are both used in major documentation sites: developer.mozilla.org & W3Schools

*Well as close as it gets

Chris Happy
  • 7,088
  • 2
  • 22
  • 49