Object-Oriented Programming with JavaScript, Part I: Inheritance: Adding Properties after the Object is Created - Doc JavaScript
Object-Oriented Programming with JavaScript, Part I: Inheritance
Adding Properties after the Object is Created
Inheritance by prototyping (Page 4) is better than inheriting by function (Page 3) because it supports dynamic inheritance. You can define superclass methods and properties after the constructor is done, and have the subclass object pick the new methods and properties, automatically. Here is an example that defines the blessyou()
function after the objects are created:
function superClass() { this.bye = superBye; this.hello = superHello; } function subClass() { this.bye = subBye; } subClass.prototype = new superClass; function superHello() { return "Hello from superClass"; } function superBye() { return "Bye from superClass"; } function subBye() { return "Bye from subClass"; } var newClass = new subClass(); superClass.prototype.blessyou = superBlessyou; function superBlessyou() { return "Bless You from SuperClass"; } function printSub() { alert(newClass.bye()); alert(newClass.hello()); alert(newClass.blessyou()); }
Notice the three lines:
superClass.prototype.blessyou = superBlessyou; function superBlessyou() { return "Bless You from superClass"; }
We define the function blessyou()
and then print it from the subclass
object:
function printSub() { var newClass = new subClass(); alert(newClass.bye()); alert(newClass.hello()); alert(newClass.blessyou()); }
Use the isPrototypeOf()
method to find out if object2
had object1
in its prototype
chain:
object1.prototype.isPrototypeOf(0bject2);
It returns true
if object2
is an object and when object1
appears in the prototype
chain of object2
. Let's look at an example:
function Person() { this.name = "Rob Roberson"; this.age = 31; } function Employee() { this.dept = "HR"; this.manager = "John Johnson"; } Employee.prototype = new Person(); var Ken = new Employee();
Ken is in the prototype
chain of Employee
, Person
, and Object
. Prove it to yourself by clicking on each class. They alert Employee.prototype.isPrototypeOf(Ken)
, Person.prototype.isPrototypeOf(Ken)
, and Object.prototype.isPrototypeOf(Ken)
, respectively.
Next: How to probe inheritance in NS with __proto__
Produced by Yehuda Shiran and Tomer Shiran
All Rights Reserved. Legal Notices.
Created: March 12, 2001
Revised: March 12, 2001
URL: https://www.webreference.com/js/column79/5.html