Objects & Prototypes
JavaScript is an object-oriented language, but it uses prototypal inheritance instead of classical inheritance (like Java). Understanding objects and prototypes is essential for mastering JavaScript.1. Objects
An object is a collection of key-value pairs. Keys are strings (or Symbols), values can be anything.Creating Objects
Computed Property Names (ES6)
Shorthand Properties (ES6)
2. The this Keyword
this is one of the most confusing parts of JavaScript. Its value depends on how a function is called, not where it’s defined.
Rules for this
| Call Type | this Value |
|---|---|
Method call (obj.fn()) | The object before the dot |
Simple call (fn()) | undefined (strict) or window (sloppy) |
| Arrow function | Inherits from enclosing scope |
Constructor (new Fn()) | The newly created object |
call/apply/bind | Explicitly set |
Examples
Arrow Functions & this
Arrow functions don’t have their own this. They inherit this from the enclosing scope.
Binding this
3. Prototypes
Every JavaScript object has a hidden property called[[Prototype]] (accessible via __proto__ or Object.getPrototypeOf()). When you access a property, JavaScript looks up the prototype chain.
The Prototype Chain
When accessingrabbit.toString():
- Check
rabbit→ Not found - Check
animal→ Not found - Check
Object.prototype→ Found!
Object.create()
The proper way to create an object with a specific prototype.
4. Constructor Functions
Before ES6 classes, constructor functions were the standard way to create objects with shared behavior.The new Keyword
When you call new Person():
- Creates a new empty object
{} - Sets the prototype to
Person.prototype - Binds
thisto the new object - Executes the constructor
- Returns the object (unless constructor returns an object)
5. ES6 Classes
Classes are syntactic sugar over constructor functions and prototypes. They don’t introduce a new OOP model.Inheritance with extends
Private Fields (ES2022)
6. Object Methods
Object.keys/values/entries
Object.assign & Spread
Object.freeze & Object.seal
Summary
- Objects: Key-value pairs. Use dot or bracket notation.
this: Depends on how a function is called. Arrow functions inheritthis.- Prototypes: Objects inherit from other objects via the prototype chain.
- Classes: Syntactic sugar over prototypes. Use
extendsfor inheritance. - Private Fields: Use
#prefix for true encapsulation (ES2022).