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 = {}
?
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 = {}
?
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:
Type safety (far and away the main reason)
Performance (possibly).
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