Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
this.constructor.super_.prototype.methodName.apply
ParentClass.prototype.methodName.apply
util.inherits(ChildClass, ParentClass);
function override(fn){
var name = fn.name;
return function(){
this.inherited = this.constructor.super_.prototype[name];
return fn.apply(this, arguments);
}
}ChildClass.prototype.methodName = override(function methodName(){
this.inherited();
// new code
})function override(class,fn){
fn.inherited = class.super_.prototype[fn.name];
return fn;
}
ChildClass.prototype.methodName = override(ChildClass,function methodName(){
methodName.inherited();
// new code
})
exports.inherits = function(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
ctor.override = function(fn){
fn.inherited = superCtor.prototype[fn.name];
ctor.prototype[fn.name] = fn;
}
};
ChildClass.override(function methodName(){
methodName.inherited();
// new code
})
util.inherits видели? Какие там могут быть оптимизации? :)
Object.create по вашему в другом не деоптимизированном коде работает медленнее, чем в этой функции, или созданный в этом месте объект отличается от созданного в другом? :) Интересная точка зрения, интересно было бы посмотреть на тесты.function override(parent, fn) {
fn.inherited = parent.prototype[fn.name];
return fn;
}
ChildClass.prototype.methodName = override(ParentClass, function methodName(par) {
methodName.inherited(par); // или methodName.inherited.apply(this, arguments);
// new code
});
function override(class,fn) { // class зарезервированное слово
fn.inherited = class.super_.prototype[fn.name];
// чем лезть через class.super_.prototype, можно сразу сюда передать родителя
// и тогда имеем fn.inherited = parent.prototype[fn.name];
return fn;
}
Использование:
// тут, соответственно, вместо ChildClass ставим ParentClass
ChildClass.prototype.methodName = override(ChildClass,function methodName(){
methodName.inherited();
// new code
})
atom.declare( 'Foo', { testPrevious: function method (arg) { console.log( method.path, arg ); } }); atom.declare( 'Bar', Foo, { testPrevious: function method (arg) { method.previous.call(this, arg); console.log( method.path, arg ); method.previous.call(this, 95612); } }); new Bar().testPrevious(42); /* Foo#testPrevious 42 * Bar#testPrevious 42 * Foo#testPrevious 95612 */
exports.inherits = function(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
util.inherits быстрее Object.create? Где в статье объяснено, что трансляторы ES6 выдают медленный говнокод? :) Вроде это вам объяснено обратное, да с примерами.util.inherits — в большинстве браузеров сейчас тот же v8. Скорость вызова метода — в 1.5 раза в вашу пользу — ну а чему удивляться — ссылка короче, получение из this и почти пустой метод. А вот скорость создания инстансов процентов на 30 у вашего ниже. И это сгенерированный код.methodName.inherited(par);, а должен — methodName.inherited.call(this, par); — и скорость сравнялась.methodName.inherited.apply(this, arguments); вместо call на jsperf — для вас всё совсем печально:c:\>node inheritance6
Instantiation test
Processing time: 2515
Call method test
Processing time: 1527
c:\>node 6to5
Instantiation test
Processing time: 2459
Call method test
Processing time: 385
Instantiation test
Processing time: 744
Call method test
Processing time: 376
Instantiation test
Processing time: 869
Call method test
Processing time: 372
apply и call всё равно не корректно. А тест на jsperf выше с call в любом v8 браузере — полностью корректен и для ноды.this не тот захватываете. Проверьте :)Instantiation test
Processing time: 656
Call method test
Processing time: 372
Instantiation test
Processing time: 524
Call method test
Processing time: 284
К тому же, оказалось, что в node.js call работает бфстрее, чем apply, это странно и непривычно
this.constructor.super_.call(this, par1, par2);
// Supertype
class Person {
constructor(name) {
this.name = name;
}
describe() {
return "Person called " + this.name;
}
}
// Subtype
class Employee extends Person {
constructor(name, title) {
super.constructor(name);
this.title = title;
}
describe() {
return super.describe() + " (" + this.title + ")";
}
}
Object.create. Если же всё таки нужно использовать суперкласс, то вызываю напрямую ParentClass.prototype.overridenMethod, нодовский inherit не использую.
Краткая заметка про наследование в Node.js