Inheritance in JavaScript
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 clas开发者_JS百科s
//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 this
works
function ClassB(sColor, sName){
this.newMethod = classA;
this.newMethod(sColor);
delete this.newMethod;
this.name = sName;
this.sayName = function(){
alert(this.name);
}
}
Is a mediocre way of doing this
function ClassB(sColor, sName){
classA.call(this, sColor);
this.name = sName;
this.sayName = function(){
alert(this.name);
}
}
var f = new ClassB("green", "boy");
f.sayName(); // boy
f.sayColor(); // green
Your basically calling the classA
constructor with your this
object.
JavaScript does not have classes, it just has objects and functions that manipulate objects. Your ClassA
function manipulates this
and so does ClassB
.
ClassA
is just a function that manipulates an object. In this case it manipulates the context
object which is this
. All ClassB
is doing is saying
- let ClassA manipulate
this
- add a property called
name
tothis
- add a method called
sayName
tothis
Bonus:
There's a better way to do OO in JavaScript
// A is a blueprint for an object with a method sayColor
var A = (function() {
var self = Object.create({});
self.sayColor = function() {
alert(this.color);
};
return self;
}());
// B is a blueprint for an object with methods sayColor and sayName
var B = (function() {
// clone the methods from A
var self = Object.create(A);
self.sayName = function() {
alert(this.name);
};
return self;
}());
// clone B and set the properties for name and color
var b = Object.create(B, {
name: { value: "boy" },
color: { value: "green" }
});
/* or use a factory
var bFactory = function(name, color) {
return Object.create(B, {
name: { value: name },
color: { value: boy }
});
}
b = bFactory("boy", "green");
*/
b.sayName();
b.sayColor();
Use Object.create
which is ES5 so use the ES5-shim to support legacy browsers.
精彩评论