Last active
August 29, 2015 13:56
-
-
Save RubaXa/8857525 to your computer and use it in GitHub Desktop.
Inherit.js (http://rubaxa.github.io/friday/2014-02-07.html)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example