In JavaScript, prototypes are used to extend the functionality of objects and their constructors. Every JavaScript object has a prototype property, which points to another object, allowing inheritance and sharing of methods between objects. Here's how prototype works in extending JavaScript:
1. Prototype and Inheritance
Each JavaScript function has a prototype
property, which is used to define methods and properties that should be shared by all instances of objects created from that function (constructor function). This is the foundation for inheritance in JavaScript.
Example:
2. Prototype Chain
Every object in JavaScript has access to its constructor’s prototype. If an object doesn’t have a property or method directly, JavaScript looks up the prototype chain to find it.
Example:
In the example above, dog
doesn't have a speak()
method, so JavaScript looks for it in the prototype chain (which is animal
in this case).
3. Extending Built-in JavaScript Objects
You can also extend built-in JavaScript objects, like Array
, String
, etc., using prototypes.
Example (extending Array):
Here, we've added a first
method to the Array
prototype that returns the first element of the array.
4. Prototypal Inheritance with Classes
In modern JavaScript (ES6+), classes are syntactical sugar over the prototype-based inheritance. When you create a class, JavaScript automatically sets up the prototype chain for you.
Example (class and prototype):
In this case, Dog
inherits from Animal
, and the prototype chain is automatically set up.
Key Takeaways:
- Prototypes are the mechanism by which JavaScript objects can inherit properties and methods from other objects.
- You can use the
prototype
property to add methods or properties to all instances of a constructor function. - JavaScript uses the prototype chain to look up properties and methods if they are not found on the object itself.
- The prototype mechanism is central to inheritance in JavaScript, both for user-defined objects and built-in objects.
No comments:
Post a Comment