Not only is that okay, it's the right way to do it. Declaring variables in your constructor just makes them variables in the constructor, it doesn't make them properties of the instance. What you're doing does make them properties, and is correct (and well-supported by IDE code-completion; e.g., later if you type zombie.
the IDE knows that zombie
probably has species
, action
, and story
, and can auto-suggest them).
Somewhat tangential, but unless you have a good reason for creating a separate story
function for each instance, put it on the object that will be assigned as the new object's prototype instead:
const Creature = function() {
this.species = null;
this.action = null;
};
Creature.prototype.story = function() {
console.log("The " +this.species +" is about to " +this.action +".");
};
If you're using constructor functions, as you're already using ES2015+ features (const
), you might consider using class
:
class Creature {
constructor() {
this.species = null;
this.action = null;
}
story() {
console.log("The " +this.species +" is about to " +this.action +".");
}
}
...as it's a bit more concise and declarative. Also, it prevents your calling Creature
without new
by mistake.
Separately, rather than
zombie = new Creature();
zombie.species = "zombie";
zombie.action = "strike";
...you might initialize those properties in the constructor:
class Creature {
constructor(species, action) {
this.species = species;
this.action = action;
}
story() {
console.log("The " +this.species +" is about to " +this.action +".");
}
}
Then:
zombie = new Creature("zombie", "strike");
(Community wiki because this is largely what the comments on the question say, just expanded a bit.)