Search code examples
javascripteloquentthisinitializing

Initializing Object Property


I've been following along Eloquent Javascript and have come across this piece of code:

var protoRabbit = {
  speak: function(line) {
    console.log("The " + this.type + " rabbit says '" +
                line + "'");
  }
};

Coming from a background in C/C++, this syntax threw me off. Where did the property type come from? Is it added to protoRabbit when we run protoRabbit.speak()? Thanks in advance.

EDIT: Thanks for the replies. I apologize as it seems that I didn't make my question very clear. What I'm confused about is whether or not the property 'type' has to exist before we initialize it. As in:

var protoRabbit = {type: "some value", speak: ... };

Is it automatically added as a property when we initialize it? If protoRabbit was const, would that violate the const initialization?


Solution

  • What I'm confused about is whether or not the property 'type' has to exist before we initialize it ... Is it automatically added as a property when we initialize it? If protoRabbit was const, would that violate the const initialization?

    You can set any key on an object at any time, without initializing it first. Whether or not the variable is const doesn't matter, because the object ref isn't being changed, the object itself is being mutated in place. You would only run into trouble if you tried assigning a different object to protoRabbit.

    var protoRabbit = {
      speak: ...
    };
    

    This creates an object with one property named speak.

    protoRabbit.type = "killer";
    

    This creates a property on protoRabbit called type. It doesn't exist until this line.

    Variables in JavaScript, specifically var, are different. Their reference is hoisted to the top of the lexical scope where they are declared, so that earlier references won't break. let doesn't get hoisted, and follows different scope semantics.