javascript inheritance, reflection and prototype chain walking? -
i'm trying figure out how can use of javascript language , how have implement myself when comes object reflection. here's intended result
// property inheritance schema (defining default props) (stored in db "schemas" table) foo bar moo baz ugh // method inheritance schema (stored in code) foo bar moo baz ugh // mytree structure + property overrides (stored in db "structs" table) mybar mybaz myugh mybar mybaz mymoo
an instance of tree object constructed mybar structure. when building each node, compose methods code, "inherited" property schema , non-default properties node defined in mybar struct itself.
the goal create a system that, given node instance of tree, can self-analyze own property inheritance path , identify @ level property defined.
this allow editing of mybar structure , indicate properties inherited defaults base schema (and @ level) , ones explicitly defined in mybar structure.
the question is, how can determined recursively analyzing .constructor , .prototype properties using js, , how need custom implemented?
i'm not sure if sufficiently clear, please ask clarification.
thanks!
you want build prototype chains.
so let's chain of inheritance is
foo -> bar -> moo.
then have object foo
prototype foo nodes.
you can create bar
object injecting foo
it's prototype chain.
var bar = object.create(foo, props)
now have bar
prototype prototype bar nodes.
then same moo
var moo = object.create(bar, props)
now let's have moo node.
then can take property know. let's call "prop1" , write simple function gives object property belongs to
var findpropertyowner = function(obj, prop) { { if (obj.hasownproperty(prop)) { return obj; } } while (obj = object.getprototypeof(obj)); }
now 1 of issues may face obj in prototype chain has no meta data telling object may want add property "name"
node prototype objects can more check is.
you may want have findpropertyowner
return tuple of (obj, count)
follows
var findpropertyowner = function(obj, prop) { var = 0; { if (obj.hasownproperty(prop)) { return [obj, i]; } } while (i++, obj = object.getprototypeof(obj)); }
this way have more information how far prototype chain property found. note when do/while loop terminates (object.getprototypeof(object.prototype) === null
) return undefined
Comments
Post a Comment