@ 261106.5raw
current

JavaScript Overview for V8 Developers

This document provides a high-level overview of how JavaScript works, focusing on concepts that are relevant for understanding V8’s implementation.

Primitives vs. Objects

JavaScript has two main categories of values:

1. Primitives

Immutable values that are passed by value.

2. Objects

Mutable collections of properties, passed by reference.

How V8 implements prototypes

JavaScript uses a prototypal inheritance model. Every object has a hidden link to another object called its prototype (internal [[Prototype]]).

Prototype Chain

Foo.prototype vs foo.__proto__

dot is not installed; install graphviz to draw this graph

digraph G {
    rankdir=TB;
    node [shape=record];
    edge [];

    Foo [label="Constructor: Foo"];
    Foo_Proto [label="Foo.prototype"];
    foo [label="Instance: foo"];
    Obj_Proto [label="Object.prototype"];
    null_node [label="null"];

    Foo -> Foo_Proto [label=".prototype"];
    Foo -> foo [label="new Foo", style=dashed];
    foo -> Foo_Proto [label="[[Prototype]]"];
    Foo_Proto -> Obj_Proto [label="[[Prototype]]"];
    Obj_Proto -> null_node [label="[[Prototype]]"];
}

__proto__ and V8 Implementation

ES6 Classes

ES6 classes are primarily syntactic sugar over JavaScript’s existing prototype-based inheritance.

class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks.`);
  }
}

Under the hood, this is equivalent to:

function Animal(name) {
  this.name = name;
}
Animal.prototype.speak = function() {
  console.log(this.name + ' makes a noise.');
};

function Dog(name) {
  Animal.call(this, name);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.speak = function() {
  console.log(this.name + ' barks.');
};

File Structure