function Person(name) {
this.name = name;
this.walk = function() {
alert(this.name + " is walking.");
};
}
Person.prototype.sayHello = function() {
alert("Hello, my name is " + this.name);
};
Person.prototype.run = function() {
alert(this.name + " is running.");
};
function Employee(name, title) {
Person.call(this, name);
this.title = title;
}
//Employee.prototype = Person.prototype; // what if using this instead?
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
Employee.prototype.sayHello = function() {
alert("Hello, my name is " + this.name + ", I'm the " + this.title);
};
// test code - overall
var txt = "Hello, World!";
var p = new Person("Jane");
//alert(Person.prototype.isPrototypeOf(p)); // output: true
//p.sayHello(); // output: Hello, my name is Jane.
//alert(typeof Person.prototype); // output: object
//txt = outputObj(Person.prototype);
// output:
// [n: sayHello - d: 0 - v: function () { alert("Hello, my name is " + this.name + "."); }]
// [n: run - d: 0 - v: function () { alert(this.name + " is running."); }]
//alert(typeof Employee.prototype); // output: object
//alert(typeof Employee.constructor); // output: function
//txt = outputObj(Employee.prototype);
//output:
//[n: constructor - d: 0 - v: function Employee(name, title) { Person.call(this, name); this.title = title; }]
//[n: sayHello - d: 0 - v: function () { alert("Hello, my name is " + this.name + ", I'm the " + this.title + "."); }]
//[n: run - d: 0 - v: function () { alert(this.name + " is running."); }]
//txt = Employee.prototype.constructor.toString();
// output: function Employee(name, title) { Person.call(this, name); this.title = title; }
var jane = new Employee("Jane", "Accountant");
//jane.sayHello(); //output: Hello, my name is Jane, I'm the Accountant.
//jane.walk(); // output: Jane is walking.
//jane.run(); // output: Jane is running.
//alert(Employee.prototype.isPrototypeOf(jane)); // output: true
//txt = jane.constructor.toString();
//output: function Employee(name, title) { Person.call(this, name); this.title = title; }
//txt = typeof jane.prototype; //output:undefined
@reference_1_Inheritance and the prototype chain_mozilla
@reference_2_Introduction to Object-Oriented JavaScript_mozilla
No comments:
Post a Comment