JavaScript Prototype

What is object prototype in JS?

In JS objects use themselves to share properties and inherit features from one another and this is done using prototype.

function Car() {
this.company = ‘Bugatti’
this.doors = 4
}

const car = new…


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Mahmoud EL-kariouny

What is object prototype in JS?

  • In JS objects use themselves to share properties and inherit features from one another and this is done using prototype.

Image description

function Car() {
  this.company = 'Bugatti'
  this.doors   = 4
}

const car = new Car();

console.log(Car.prototype);

// Car{}
  • The prototype is itself an object so the prototype will have its prototype making what is called a prototype chain.
  • The chain ends when we reach a prototype that has Null for its prototype.

  • Prototype inheritance is used to add methods and properties to the objects.

function Car() {
  this.company = 'Bugatti'
  this.doors   = 4
}


const car1 = new Car();
const car2 = new Car();

Car.prototype.model = 'Bugatti veyron'

console.log(Car.prototype)

console.log(car1.model)
console.log(car2.model)


// Output

// Car { model: 'Bugatti veyron' }
// Bugatti veyron
// Bugatti veyron

Prototype are used because:

  1. They use less memory.
  2. There is less coupling.
  3. Prototypes can be easily extended.
Learn more about prototype

Guide to JavaScript’s Prototype

Connect with Me 😊

🔗 Links

linkedin

twitter


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Mahmoud EL-kariouny


Print Share Comment Cite Upload Translate Updates
APA

Mahmoud EL-kariouny | Sciencx (2022-10-25T00:25:53+00:00) JavaScript Prototype. Retrieved from https://www.scien.cx/2022/10/25/javascript-prototype/

MLA
" » JavaScript Prototype." Mahmoud EL-kariouny | Sciencx - Tuesday October 25, 2022, https://www.scien.cx/2022/10/25/javascript-prototype/
HARVARD
Mahmoud EL-kariouny | Sciencx Tuesday October 25, 2022 » JavaScript Prototype., viewed ,<https://www.scien.cx/2022/10/25/javascript-prototype/>
VANCOUVER
Mahmoud EL-kariouny | Sciencx - » JavaScript Prototype. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/10/25/javascript-prototype/
CHICAGO
" » JavaScript Prototype." Mahmoud EL-kariouny | Sciencx - Accessed . https://www.scien.cx/2022/10/25/javascript-prototype/
IEEE
" » JavaScript Prototype." Mahmoud EL-kariouny | Sciencx [Online]. Available: https://www.scien.cx/2022/10/25/javascript-prototype/. [Accessed: ]
rf:citation
» JavaScript Prototype | Mahmoud EL-kariouny | Sciencx | https://www.scien.cx/2022/10/25/javascript-prototype/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.