Skip to content

Instantly share code, notes, and snippets.

@BiosBoy
Created August 19, 2024 09:56
Show Gist options
  • Save BiosBoy/909b5f5fba6f3df3335ed7321cf1886d to your computer and use it in GitHub Desktop.
Save BiosBoy/909b5f5fba6f3df3335ed7321cf1886d to your computer and use it in GitHub Desktop.
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
const alice = new Person('Alice');
function Developer(name, language) {
Person.call(this, name); // Call the parent constructor
this.language = language;
}
// Inherit from Person
Developer.prototype = Object.create(Person.prototype);
Developer.prototype.constructor = Developer;
Developer.prototype.code = function() {
console.log(`${this.name} is coding in ${this.language}`);
};
const bob = new Developer('Bob', 'JavaScript');
bob.greet(); // Outputs: Hello, my name is Bob
bob.code(); // Outputs: Bob is coding in JavaScript
console.log(bob.__proto__ === Developer.prototype); // true
console.log(Object.getPrototypeOf(bob) === Developer.prototype); // true
bob.greet = function() {
console.log(`Hi, I'm ${this.name} and I love ${this.language}`);
};
bob.greet(); // Outputs: Hi, I'm Bob and I love JavaScript
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment