tastypie
Version:
Tastypie is a webservice API framework for Node.js based on Django's Tastypie Framework. It provides a convenient, yet powerful and highly customizable, abstraction for creating REST-style interfaces
91 lines (68 loc) • 2.72 kB
JavaScript
/*
prime
- prototypal inheritance
*/"use strict"
var hasOwn = require("mout/object/hasOwn"),
mixIn = require("mout/object/mixIn"),
create = require("mout/lang/createObject"),
kindOf = require("mout/lang/kindOf")
var hasDescriptors = true
try {
Object.defineProperty({}, "~", {})
Object.getOwnPropertyDescriptor({}, "~")
} catch (e){
hasDescriptors = false
}
// we only need to be able to implement "toString" and "valueOf" in IE < 9
var hasEnumBug = !({valueOf: 0}).propertyIsEnumerable("valueOf"),
buggy = ["toString", "valueOf"]
var verbs = /^constructor|inherits|mixin$/
var implement = function(proto){
var prototype = this.prototype
for (var key in proto){
if (key.match(verbs)) continue
if (hasDescriptors){
var descriptor = Object.getOwnPropertyDescriptor(proto, key)
if (descriptor){
Object.defineProperty(prototype, key, descriptor)
continue
}
}
prototype[key] = proto[key]
}
if (hasEnumBug) for (var i = 0; (key = buggy[i]); i++){
var value = proto[key]
if (value !== Object.prototype[key]) prototype[key] = value
}
return this
}
var prime = function(proto){
if (kindOf(proto) === "Function") proto = {constructor: proto}
var superprime = proto.inherits
// if our nice proto object has no own constructor property
// then we proceed using a ghosting constructor that all it does is
// call the parent's constructor if it has a superprime, else an empty constructor
// proto.constructor becomes the effective constructor
var constructor = (hasOwn(proto, "constructor")) ? proto.constructor : (superprime) ? function(){
return superprime.apply(this, arguments)
} : function(){}
if (superprime){
mixIn(constructor, superprime)
var superproto = superprime.prototype
// inherit from superprime
var cproto = constructor.prototype = create(superproto)
// setting constructor.parent to superprime.prototype
// because it's the shortest possible absolute reference
constructor.parent = superproto
cproto.constructor = constructor
}
if (!constructor.implement) constructor.implement = implement
var mixins = proto.mixin
if (mixins){
if (kindOf(mixins) !== "Array") mixins = [mixins]
for (var i = 0; i < mixins.length; i++) constructor.implement(create(mixins[i].prototype))
}
// implement proto and return constructor
return constructor.implement(proto)
}
module.exports = prime