Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
function MyClass(…) {
…
}
MyClass.prototype = Object.extend(Object.create(MyOtherClass.prototype), {
constructor: MyClass,
…
});Object.inherit = function(Child, Parent) {
(Child.prototype = Object.create(Child.superclass = Parent.prototype)).constructor = Child;
}
/** @constructor */
function A() {
this.say = function() { console.log("may") }
this.init = function() { console.log("init A instance") }
}
/** @constructor */
function B() {
B.superclass.constructor.apply(this, arguments);//A.apply(this, arguments);
/** @override */
this.say = function() { console.log("gav") }
var superInit = this.init;
this.init = function() {
superInit();//Parent `init` function
console.log("init B instance")
}
}
Object.inherit(B, A);
var b = new B;
b.init();
>> init A instance
>> init B instance
b.say();
>> gav
child.statConstructor.prototype.proto = function() {
return;
}
child.statConstructor.prototype.proto = Function()
// вместо
if (parent && ("statConstructor" in parent) && parent.statConstructor && typeof (parent.statConstructor) === "function") { ... }
// достаточно
if (parent && typeof parent.statConstructor == "function") { ... }
* У классов есть параметр stat, предназначенный для статических ф-ий и данных.
* Можно запретить наследовать метод, объявляя его без prototype.
try {
delete child.stat[name];
} catch(e) {
}
if(child.stat.construct) {
// Вызывается при создании класса или создании потомка без stat.construct
child.stat.construct();
}
// уж лучше так
if(typeof child.stat.construct == 'function') {
// Вызывается при создании класса или создании потомка без stat.construct
child.stat.construct();
}
arguments.callee.caller
А мне хочется, чтобы все объекты, наследники класса Foo имели уникальный id и предупреждали пользователя, что умеют взрываться.
Для реализации этого — я создаю специальный метод cnstruct (constructor — уже занято), и выполняю его при создании каждого объекта. Чтобы не забыть его выполнять, отказываюсь от создания объектов через new Foo() и создаю объекты через статический метод Foo.stat.create().
function createClass(super, ext){
if (!super)
super = Function();
var superConstruct = super.prototype.cunstruct;
var newClass = function(){
if (typeof superConstruct == 'function')
superConstruct.apply(this, arguments)
if (typeof this.construct == 'function')
this.construct.apply(this, arguments);
}
var tempClass = Function();
tempClass.prototype = super.prototype;
newClass.prototype = new tempClass();
for (var key in ext)
newClass.prototype[key] = ext[key];
return newClass;
}
var Foo = function(a, b){ .. }
var Bar = function(c, a){
// делаем что-то до
Foo.call(this, a, 'contant value');
// Делаем что-то после
}
Bar.prototype = new Foo();
child.prototype.protoFunc = child.statConstructor.prototype.protoFunc = function(callerFuncName, args, applyFuncName) {
/*
* Позволяет вызвать функцию более ранней версии в иерархии прототипов ...
var Foo = function(){};
Foo.prototype = {
method: function(){ .. }
};
var Bar = function(){};
Bar.prototype = new Foo();
Bar.prototype.method = function(){
Foo.prototype.method.apply(this, arguments);
}
Мой extend и стиль наследования классов