DEV Community

Discussion on: Looking at the Prototype

Collapse
 
peerreynders profile image
peerreynders • Edited

prototype is the property you set on a constructor function - any objects created via new will have that object as their prototype.

// Constructor function
function Car(make, model) {
  if (typeof make === 'string') this.make = make;
  if (typeof model === 'string') this.model = model;
}

function getCarInfo() {
  return `${this.make} ${this.model}`;
}

Car.prototype = {
  make: 'Default',
  model: 'Default',
  getCarInfo,
};

const volvo = new Car('Volvo', 'S80');

console.assert(volvo.getCarInfo() === 'Volvo S80');
Enter fullscreen mode Exit fullscreen mode

While the actual object prototype link is an internal property, i.e. it's implementation dependent to allow for optimization, Firefox's JavaScript engine SpiderMonkey exposed it with __proto__ which was soon copied by other browsers.

ES2015:
1.) deprecates __proto__
2.) turned __proto__ into a getter/setter.

__proto__ in ECMAScript 6

Now if you want to get the prototype of an object use Object.getPrototypeOf() and you can create an object with a prototype with Object.create()

function getCarInfo() {
  return `${this.make} ${this.model}`;
}

const car = {
  make: 'Default',
  model: 'Default',
  getCarInfo,
};

const volvo = Object.create(car);
volvo.make = 'Volvo';
volvo.model = 'S80';

console.assert(volvo.getCarInfo() === 'Volvo S80');
Enter fullscreen mode Exit fullscreen mode

JavaScript's prototypal inheritance is based on Self.