Creating and initializing a prototype
suggest changevar Human = function() {
this.canWalk = true;
this.canSpeak = true;
};
Human.prototype.greet = function() {
if (this.canSpeak) {
this.name = "Steve";
console.log('Hi, I am ' + this.name);
} else {
console.log('Sorry, I cannot speak');
}
};
new runs the constructor, so canSpeak is set:
var obj = new Human();
obj.greet(); // Hi, I am Steve
Object.create(Human.prototype) does not run Human, so canSpeak stays unset and greet takes the other branch.
Detailed Explanation
var Human = function() {
this.canSpeak = true;
};
// Basic greet function which will greet based on the canSpeak flag
Human.prototype.greet = function() {
if (this.canSpeak) {
console.log('Hi, I am ' + this.name);
}
};
var Student = function(name, title) {
Human.call(this); // runs Human so this gets its own properties
this.name = name;
this.title = title;
};
Student.prototype = Object.create(Human.prototype);
Student.prototype.constructor = Student;
Student.prototype.greet = function() {
if (this.canSpeak) {
console.log('Hi, I am ' + this.name + ', the ' + this.title);
}
};
var Customer = function(name) {
Human.call(this); // inheriting from the base class
this.name = name;
};
Customer.prototype = Object.create(Human.prototype); // creating the object
Customer.prototype.constructor = Customer;
var bill = new Student('Billy', 'Teacher');
var carter = new Customer('Carter');
var andy = new Student('Andy', 'Bill');
var virat = new Customer('Virat');
bill.greet();
// Hi, I am Billy, the Teacher
carter.greet();
// Hi, I am Carter
andy.greet();
// Hi, I am Andy, the Bill
virat.greet();
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents