I am reading this one JS book that talks about inheritance and I am really confused at what each line is doing. Can someone let me know if my understanding is correct or not.
function classA(sColor){
this.color = sColor;
this.sayColor = function (){
alert(this.color);
};
}
function ClassB(sColor, sName){
this.newMethod = classA; //assigning a reference to a parent class
this.newMethod(sColor); //calling the constructor of the parent class
//question: so what is 'this' then? from my understanding when we call 'new ClassB('a','b')'
//we instantiate a new object and that new object becomes the 'this' in this case. Does this
//line mean we are converting the this to classA?
delete this.newMethod; //deleting reference to the CONSTRUCTOR of the parent class
this.name = sName;
this.sayName = function(){
alert(this.name);
}
}
How
thisworksIs a mediocre way of doing this
Your basically calling the
classAconstructor with yourthisobject.JavaScript does not have classes, it just has objects and functions that manipulate objects. Your
ClassAfunction manipulatesthisand so doesClassB.ClassAis just a function that manipulates an object. In this case it manipulates thecontextobject which isthis. AllClassBis doing is sayingthisnametothissayNametothisBonus:
There’s a better way to do OO in JavaScript
Use
Object.createwhich is ES5 so use the ES5-shim to support legacy browsers.