liveBook · Manning

Instance variable

As explained in Secrets of the JavaScript Ninja, Second Edition

A property that belongs directly to a particular object instance rather than being inherited from its prototype.

An instance property belongs directly to one object. In a constructor, assigning a value through `this` creates that property on the new instance. section 7.2.1

That direct placement affects lookup and reuse:

  • If an instance and its prototype have properties with the same name, the instance property takes precedence; lookup need not continue to the prototype. section 7.2.1
  • Each instance gets its own constructor-created properties, while instances share access to properties on the prototype. Repeated method copies may be worth avoiding when creating many objects. section 7.2.1
Listing 7.3. Observing the precedence of initialization activities
 function Ninja(){
  this.swung = false;                            #A
  this.swingSword = function(){                  #B
    return !this.swung;                          #B
  };
 }
 Ninja.prototype.swingSword = function(){        #C
   return this.swung;                            #C
 };                                              #C

 const ninja = new Ninja();                                        #D
 assert(ninja.swingSword(),                                        #D
       "Called the instance method, not the prototype method.");   #D

The Ninja example contrasts an instance method with a same-named prototype method, making the precedence visible. section 7.2.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains constructor assignment, property precedence, and per-instance copies, then flags repeated methods as a concern for many objects.
Examples
Uses Ninja instances with `swung` and competing `swingSword` methods to demonstrate property ownership and precedence.
What you can do after
Understand which same-named property is found and why constructor-created methods are duplicated across instances.
How it connects
Links instance properties to constructor functions, prototype properties, and prototype-chain lookup.

Also explained in

Compare how 4 books explain instance variable →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.