classloader - Creating different instance of the same prototype in Javascript -
i'd create 2 different "instances" of same prototype in javascript. please note word "instances" here not refer "instantiated classes" 2 distinct class instances (one specific class has been loaded 2 different class loaders in java terms example).
assuming have object:
var protoobj = { prop: "", method: function () { // stuffz } } protoobj.method.staticproperty = 0; function childobj (prop) { this.prop = prop; } childobj.prototype = protoobj; var child1 = new childobj("first child"); var child2 = new childobj("second child"); console.log("prop:", child1.prop); //prints "prop: first child" console.log("prop:", child2.prop); //prints "prop1: second child" child1.method.staticproperty = 1; child2.method.staticproperty = 2; console.log("child1 static:", child1.method.staticproperty); //prints "child1 static: 2" <-- wanted 1. want each instance have own "parent" console.log("child2 static:", child2.method.staticproperty); //prints "child2 static: 2"
my goal child1.method.staticproperty
have different value child2.method.staticproperty
you might ask why needed? storing state in function properties wrong indeed, code above comes typescript compiler compiles "class statics" properties of javascript constructor functions. need have different static values same class name.
note in case protoobj
javascript applicationapi (a 20k line file) , our goal able create 2 distinct instances of application while loading library once.
my goal
child1.method.staticproperty
have different valuechild2.method.staticproperty
that possible when 2 methods distinct, there 2 prototype objects objects inherit - not possible without creating 2 protoobj
s or cloning it, said don't want to.
note in case
protoobj
javascript applicationapi (a 20k line file) , our goal able create 2 distinct instances of application
include script file twice execute twice , create 2 distinct objects:
<script type="text/javascript" src="applicationapi.js"></script> <script type="text/javascript"> console.assert(childobj.prototype == protoobj); var firstinstance = childobj; protoobj.method.staticproperty = 1; </script> <script type="text/javascript" src="applicationapi.js"></script> <script type="text/javascript"> console.assert(childobj.prototype == protoobj); var secondinstance = childobj; protoobj.method.staticproperty = 2; </script> <script type="text/javascript"> console.log(new firstinstance); console.log(new secondinstance); console.log(firstinstance !== secondinstance); </script>
notice need suggests fault in design of api library.
…while loading library once.
just send appropriate caching headers , it'll done implicitly.
Comments
Post a Comment