Binding a function to a prototype in a JavaScript inheritance hierarchy -
what want retrofit serialisation method existing javascript type, member of inheritance tree. working, function operating on parent type rather type trying associate with. take basic example:
function animal( species, population ) { this.species = species; this.population = population; } animal.prototype.getdetail = function() { return "species: "+this.species+" population: "+this.population; } function mammal( species, population, bodytemperature ) { animal.apply(this, [species, population]); this.bodytemperature = bodytemperature; } mammal.prototype= new animal(); mammal.constructor = mammal; var serialise= { init: function() { mammal.prototype.serialise = this.serialisemammal.bind(mammal.prototype); }, serialisemammal: function() { return { species: this.species, population: this.population, bodytemperature: this.bodytemperature }; } } serialise.init(); var bob = new mammal("human", 7000000000, 36.6); console.log( bob.serialise() );
what happening serialise
function running in context of animal
type correct because prototype of mammal
, if try bind directly mammal
, nothing happens @ all. once again, find myself out of depth in javascript's scope.
the reason doing keep serialisation/deserialisation in 1 place, it's there if need it, don't have have included- guess in language might behaving mixin.
what need ensure call of serialise()
on instance of mammal
type correctly apply serialise.serialisemammal()
function in context of current instance? there way of doing without binding functions individual instances when created?
i'm trying improve own expertise language , doing things in more of javascript way, if whole approach totally wack or against grain of language, know.
i not understand why want decorate way, opposed putting specialized serialisemammal
directly on mammal.prototype
, below:
mammal.prototype.s2 = function() { return { species: this.species, population: this.population, bodytemperature: this.bodytemperature }; };
i called s2
not conflict. identical code serialisemammal
. however, if prefer decorator-style pattern have used, need do:
var serialise= { init: function() { mammal.prototype.serialise = this.serialisemammal; }, serialisemammal: function() { return { species: this.species, population: this.population, bodytemperature: this.bodytemperature }; } }
within context of init
, this
refers serialise
, this.serialisemammal
function have. function, nothing more. when next call bob.serialise()
, function called in context of moment. this, this
inside of bob.serialise()
, code serialisemammal
, set bob
.
here fiddle it. http://jsfiddle.net/6un6qho1/1/
Comments
Post a Comment