A class is defined using the class
keyword. It contains a constructor for initializing properties and methods to define behavior.
class Animal {
name: string; // Public by default
constructor(name: string) {
this.name = name;
}
speak() {
return `${this.name} makes a noise`;
}
}
const dog = new Animal("Dog");
console.log(dog.speak()); // Dog makes a noise
class Animal {
static species = "Mammal"; // Static property
name: string;
constructor(name: string) {
this.name = name;
}
static info() {
return `Animals belong to the ${this.species} category.`;
}
}
console.log(Animal.species); // Mammal
console.log(Animal.info()); // Animals belong to the Mammal category.
const dog = new Animal("Dog");
// console.log(dog.species); Error: Static property is not accessible via instance
instanceof
vs Object.getPrototypeOf()
instanceof
checks if an object is an instance of a class by traversing the entire prototype chain. Best for verifying class inheritance.Object.getPrototypeOf()
returns the immediate prototype of an object. Best for retrieving an object's prototype structure.class Animal {}
class Dog extends Animal {}
const dog = new Dog();
console.log(dog instanceof Dog); // true
console.log(dog instanceof Animal); // true
console.log(Object.getPrototypeOf(dog) === Dog.prototype); // true
console.log(Object.getPrototypeOf(Dog.prototype) === Animal.prototype); // true
console.log(dog.constructor === Dog); // true
console.log(dog.constructor === Animal); // false