What are JavaScript objects and prototypes?
Detailed Explanation
JavaScript is a prototype-based language where objects can inherit directly from other objects.
Creating Objects:
// Object literal
const obj = { name: "John", age: 30 };// Constructor function
function Person(name) {
this.name = name;
}
const person = new Person("John");
// Object.create()
const obj = Object.create(prototype);
Prototype:
Every function has a prototype property, and every object has a __proto__ property.
function Person(name) {
this.name = name;
}Person.prototype.greet = function() {
return "Hello, " + this.name;
};
const john = new Person("John");
console.log(john.greet()); // "Hello, John"
Prototype Chain:
When accessing a property, JavaScript looks:
1. On the object itself
2. On the object's prototype
3. Up the prototype chain until Object.prototype
4. Returns undefined if not found
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts