Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
function A(param) {
if (!param) {
throw 'Param required';
}
this.param = param;
}
A.prototype.x = 10;
var a = new A(20);
alert([a.x, a.param]); // 10, 20
function B() {}
B.prototype = new A(); // Ошибка
SubClass.prototype.getName = function() {
return "SubSubClass(id = " + this.getId() + ") extends " + SubClass.call(this);
}
SubClass.prototype.getName = function() {
return "SubSubClass(id = " + this.getId() + ") extends " + SubClass.prototype.getName.call(this);
}
alert(1..toString()); // "1"
Function.prototype.inheritsFrom = function( parentClassOrObject ){
if ( parentClassOrObject.constructor == Function )
{
//Normal Inheritance
this.prototype = new parentClassOrObject;
this.prototype.constructor = this;
this.prototype.parent = parentClassOrObject.prototype;
}
else
{
//Pure Virtual Inheritance
this.prototype = parentClassOrObject;
this.prototype.constructor = this;
this.prototype.parent = parentClassOrObject;
}
return this;
}
// Абстрактный базовый класс (по крайней мере, как его называет автор:))
LivingThing = {
beBorn : function(){
this.alive = true;
}
}
// Класс, который, с одной стороны, обращается к методам родительского
// А с другой стороны, создаёт объекты, не зная конкретного своего наследника
function Mammal(name){
this.name=name;
this.offspring=[];
}
Mammal.inheritsFrom( LivingThing );
Mammal.prototype.haveABaby=function(){
this.parent.beBorn.call(this);
var newBaby = new this.constructor( "Baby " + this.name );
this.offspring.push(newBaby);
return newBaby;
}
//
function Cat( name ){
this.name=name;
}
Cat.inheritsFrom( Mammal );
Cat.prototype.haveABaby=function(){
var theKitten = this.parent.haveABaby.call(this);
alert("mew!");
return theKitten;
}
Попытка классификации и анализа существующих подходов к наследованию в Javascript