Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
In JavaScript, every object has a hidden link to another object called its prototype. Think of it as a parent that objects can inherit properties and methods from!
Every object has a hidden property called __proto__ that links to its prototype
const person = { name: 'Alice' };
// Check the prototype
console.log(person.__proto__);
// Object.prototype (the base object)
// Access inherited methods
console.log(person.toString()); // '[object Object]'
// toString() comes from Object.prototype!How objects find properties
When you create a constructor function, JavaScript automatically creates a prototype property where you can add shared methods
function Person(name) {
this.name = name;
}
// Add method to prototype
Person.prototype.greet = function() {
console.log('Hi, I am ' + this.name);
};
const alice = new Person('Alice');
const bob = new Person('Bob');
// Both use the same method from prototype
alice.greet(); // 'Hi, I am Alice'
bob.greet(); // 'Hi, I am Bob'Shared methods for all instances
When you access a property, JavaScript searches in order:
How property lookup works
Use hasOwnProperty() to check if a property exists directly on the object (not inherited)
function Person(name) {
this.name = name;
}
Person.prototype.species = 'Human';
const alice = new Person('Alice');
// 'name' is own property
console.log(alice.hasOwnProperty('name')); // true
// 'species' is inherited from prototype
console.log(alice.hasOwnProperty('species')); // false
// But alice can still access it
console.log(alice.species); // 'Human'Distinguishing own vs inherited properties
You CAN add methods to built-in prototypes, but generally shouldn't in production code!
// Add method to Array prototype (not recommended!)
Array.prototype.myMethod = function() {
return this.length;
};
const arr = [1, 2, 3];
console.log(arr.myMethod()); // 3 (all arrays have it now)
// Better: Create your own constructor
function MyArray() {
Array.call(this);
}
MyArray.prototype = Object.create(Array.prototype);
MyArray.prototype.myMethod = function() {
return this.length;
};For learning purposes only!
__proto__ directly (deprecated)__proto__