// Define the Person constructor
function Person(name) {
this.name = name;
};
// Add a couple of methods to Person.prototype
Person.prototype.walk = function () {
console.log("I am walking!");
};
Person.prototype.sayHello = function () {
console.log("Hello, I'm " + this.name + ".");
};
// Define the Student constructor
function Student(name, subject) {
// Initialize our Student-specific properties
this.subject = subject;
// Call the parent constructor function in own context
Person.call(this, name);
};
// Create a Student.prototype object that inherits from Person.prototype
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
// Override the "sayHello" method
Student.prototype.sayHello = function () {
// if we want to still run the parent method, we call it in our context
Person.prototype.sayHello.call(this);
console.log("I'm studying " + this.subject + ".");
};
// Add a "sayGoodBye" method
Student.prototype.sayGoodBye = function () {
console.log("Goodbye!");
};
// Example usage:
var student1 = new Student("Janet", "Applied Physics");
student1.sayHello();
student1.walk();
student1.sayGoodBye();
// Check that instanceof works correctly
console.log(student1);
console.log('I am a Person:', student1 instanceof Person);
console.log('I am a Student:', student1 instanceof Student);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.