Skip to content

Instantly share code, notes, and snippets.

@RubaXa
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RubaXa/8857525 to your computer and use it in GitHub Desktop.
Save RubaXa/8857525 to your computer and use it in GitHub Desktop.
/**
* OOP
* @author RubaXa <trash@rubaxa.org>
*/
(function (){
/**
* Создание «родительского» метода
* @param {*} fn
* @param {*} parent
* @returns {*}
* @private
*/
function _parentize(fn, parent) {
if (typeof fn === 'function') {
fn.parent = parent;
}
return fn;
}
/**
* Примитивное наследование
* @param {Function|Object} Class
* @param {Object} [methods]
* @returns {Function}
* @private
*/
function inherit(Class, methods) {
if (arguments.length === 1) {
methods = Class;
Class = methods.constructor;
Class.fn = Class.prototype = methods;
return inherit.apply(Class);
}
var key,
ClassExt = _parentize(methods.hasOwnProperty('constructor') ? methods.constructor : function (a, b, c) {
switch (arguments.length) {
case 1: Class.call(this, a); break;
case 2: Class.call(this, a, b); break;
case 3: Class.call(this, a, b, c); break;
default: Class.apply(this, arguments); break;
}
}, Class)
;
// Наследуем статические методы и свойства
for (key in Class) {
if (Class.hasOwnProperty(key)) {
ClassExt[key] = Class[key];
}
}
// Наследуем
ClassExt.prototype = (function () {
var F = function () {};
F.prototype = Class.fn;
return new F;
})();
// Быстрый доступ к прототипу
ClassExt.fn = ClassExt.prototype;
// Методы класса
for (key in methods) {
ClassExt.fn[key] = _parentize(methods[key], ClassExt.fn[key]);
}
// Выправляем конструктор
ClassExt.fn.constructor = ClassExt;
return ClassExt;
}
/**
* Подмешать методы
* @param {Function} target
* @returns {Function}
*/
inherit.apply = function (target) {
target.extend = function (methods) {
return inherit(this, methods);
};
return target;
};
// Export
if( typeof define === "function" && define.amd ){
define(function (){
return inherit;
});
} else if( typeof module != "undefined" && module.exports ){
module.exports = inherit;
}
else {
window['inherit'] = inherit;
}
})();
@RubaXa
Copy link
Author

RubaXa commented Jul 28, 2014

Example

/**
 * @class Hello
 */
var Hello = inherit(/** @lends Hello.prototype */ {
   constructor: function () {
        this.str = "Hello";
    },
    toString: function () {
        return this.str; 
    }
});


/**
 * @class      HelloWorld
 * @extends  Hello
 */
var HelloWorld = Hello.extend(/** @lends HelloWorld.prototype */ {
   constructor: function __() {
        __.parent.call(this); // parent/super
        this.str += " World!";
    }
});


new HelloWorld().toString(); // "Hello World!"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment