Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Object Prototypes in JavaScript

Object Prototypes in JavaScript

Object Prototypes in JavaScript


What is a Prototype?

  • Every JavaScript object has an internal link to another object called its prototype.

  • The prototype object provides inherited properties and methods to the original object.

  • This is the core of JavaScript’s prototype-based inheritance system.


How Prototypes Work

  • When you access a property or method on an object, JavaScript first looks on the object itself.

  • If it doesn’t find it, it looks up the prototype chain until it finds the property or reaches null.

  • The prototype chain allows sharing behavior among multiple objects.


Accessing Prototype

  • Use Object.getPrototypeOf(obj) to get the prototype of an object.

const obj = {};console.log(Object.getPrototypeOf(obj) === Object.prototype);  // true

Setting Prototype

  • Use Object.create(proto) to create a new object with a specified prototype.

const animal = {  speak() {    console.log("Animal sound");  }};const dog = Object.create(animal);dog.speak();  // Animal sound

Constructor Functions and Prototypes

  • Functions have a property prototype.

  • When using new, the created object’s prototype is set to the function’s prototype.

function Person(name) {  this.name = name;}Person.prototype.greet = function() {  console.log("Hello, " + this.name);};const alice = new Person("Alice");alice.greet();  // Hello, Alice

ES6 Classes Use Prototypes Underneath

class Person {  constructor(name) {    this.name = name;  }    greet() {    console.log("Hello, " + this.name);  }}const bob = new Person("Bob");bob.greet();  // Hello, Bob

This works by adding methods to Person.prototype.


Prototype Chain Example

const animal = { eats: true };const rabbit = Object.create(animal);rabbit.jumps = true;console.log(rabbit.jumps);  // trueconsole.log(rabbit.eats);   // true (from prototype)

Summary

ConceptDescription
PrototypeObject linked internally to provide inheritance
Prototype ChainChain of prototypes looked up for properties
prototype PropertyHolds shared methods for constructor functions
Object.create()Creates object with specific prototype

Want examples on modifying prototypes or prototype pitfalls?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql