Как сохранить ссылку на себя в супер-конструкторе?
var Super = ( function( ){
function Super( args ){
this.init( args );
}
Super.prototype = {
name: undefined,
constructor: Super,
init: function( args ){
this.name = args.name;
},
toString: function( ){
return this.name;
}
};
return Super;
}( ) );
var Sub = ( function( SUPER ){
function Sub( args ){
SUPER.call( this, args );
}
Sub.prototype = Object.create( SUPER.prototype );
Sub.prototype.constructor = Sub;
Sub.prototype.init = function( args ){
};
return Sub;
}( Super ) );
var subOne = new Sub( {name: 'sub_1'} );
Возможно ли как-то сохранить ссылку на себя в объекте Super, для того чтобы не заниматься копипастом при переопределении методов в потомках?
Добавлено:
Или это самое время для приватных областей? Если делать так, то это не будет считаться нехорошо?
var Super = ( function( ){
var _context,
_init = function( args ){
_context.name = args.name;
};
function Super( args ){
// this.init( args );
_context = this;
_init( args );
}
Super.prototype = {
name: undefined,
constructor: Super,
super: Object,
toString: function( ){
return this.name;
}
};
return Super;
}( ) );
var Sub = ( function( SUPER ){
var _context,
_init = function( args ){
// ...
};
function Sub( args ){
SUPER.call( this, args );
_context = this;
_init( args );
}
Sub.prototype = Object.create( SUPER.prototype );
Sub.prototype.constructor = Sub;
Sub.prototype.super = SUPER;
return Sub;
}( Super ) );
var subOne = new Sub( {name: 'sub_1'} );
var subTwo = new Sub( {name: 'sub_2'} );
console.log( subOne.toString( ), subTwo.toString( ) ); // sub_1 sub_2
Источник: Stack Overflow на русском