Skip to content

Instantly share code, notes, and snippets.

@zythum
Created May 27, 2015 09:16
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 zythum/6308c852b2edc089bb97 to your computer and use it in GitHub Desktop.
Save zythum/6308c852b2edc089bb97 to your computer and use it in GitHub Desktop.
React inherit
var Extend = (function (prototype, apply) {
function assert(condition, message) {
if (!condition) {
message = message || "Assertion failed"
if (typeof Error !== "undefined") throw new Error(message);
throw message
}
}
function isFunction (obj) { return typeof obj === "function" }
function mixin (target, obj) {
var length = arguments.length, i = 1, mixin
while (i < length) {
mixin = arguments[i++]
for (var name in mixin) {
if (mixin.hasOwnProperty(name)) {
target[name] = mixin[name]
}
}
}
return target
}
function methodWarpper (superClass, methodName, methodContent) {
return function () {
this.super = superClass ? function () {
return superClass[prototype][methodName][apply](this, arguments)
} : undefined
var result = methodContent[apply](this, arguments)
delete this.super
return result
}
}
function Extend (superClass, def) {
var Constructor = function r(e, t) { this.props=e,this.context=t; };
var proto = superClass ? (function (E) {
return E = function () {}, E[prototype] = superClass[prototype], new E
}()) : Constructor[prototype]
return (function extension (def) {
var _proto = {}
if (isFunction(def)) {
def[apply](_proto)
} else {
_proto = def
}
for (var i in _proto) {
if (_proto.hasOwnProperty(i)) {
assert(i !== "super", "proto.super cannot be used!!")
proto[i] = isFunction(_proto[i]) ?
methodWarpper(superClass, i, _proto[i]) : _proto[i]
}
}
proto.constructor = Constructor
Constructor[prototype] = proto
Constructor.extension = extension
return Constructor
}(def))
}
return Extend
}("prototype", "apply"))
var ParentClass = Extend(React.Component, function () { //is function
this.render = function () {
return <div>Hi</div>
}
})
var SonClass = Extend(ParentClass, { //alse can be object
render: function () {
var rs = this.super()
return <div>{rs.props.children} World!</div>
}
})
ParentClass.extension({ //some, can be function alse can be object
render: function () {
return <div>Hello</div>
}
})
React.render(<div><ParentClass/><SonClass/></div>, document.body)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment