private static dynamic BooleanConstructor(this JS js, dynamic value) { dynamic b = new JSObject(); b.JSTypeName = "Boolean"; // Set up prototype dynamic p = new JSObject(); b.Prototype = b.GetPrototype(p); // Calculate the primitive value bool _primitiveValue = true; //default to true and only set to false when needed dynamic v = (value is JSObject && !(value is JSUndefined || value is JSNaN)) ? value.valueOf() : value; if (v == null || (v is String && (v == "" || v == "false")) || (v is Boolean && v == false) || ((v is Int32 || v is Int64 || v is Int16) && v == 0) || v is JSNaN || v is JSUndefined) { _primitiveValue = false; } // Set up instance items b.valueOf = new Func<bool>(() => _primitiveValue); b.toString = new Func<string>(() => _primitiveValue ? "true" : "false"); //Consider using String() here return b; }
public void PrototypeFun() { dynamic s = JS.cs.NewString("hello"); dynamic thing = new JSObject(); thing.Prototype.bizbuzz = new Func<string, string>((name) => "hello, " + name); s.Prototype.foobar = new Func<bool>(() => true); // Check it doesn't inadvertantly set ALL Prototypes from root object to have foobar // bizbuzz method available on all objects Assert.AreEqual("hello, tony", s.bizbuzz("tony")); Assert.AreEqual("hello, tony", thing.bizbuzz("tony")); // foobar set oon string prototype, but not exposed to object Assert.IsTrue(s.foobar()); Assert.IsFalse(thing.foobar); // Feature detection -- not set on object prototype Assert.AreEqual(3, thing.Count); //foobar should not show up on JSObject's prototype.... Assert.AreEqual(4, s.Count); // foobar and bizbuzz are available to previously created string instances // Create new string prototype and set it dynamic newPrototype = new JSObject(); newPrototype.skunkWorks = "skunky!"; s.SetPrototype(newPrototype); // skunkWorks now available on string Assert.AreEqual(3, thing.Count); // Updating string's prototype shouldn't mess with Object Assert.IsFalse(thing.skunkWorks); // Feature detection - make sure skunkWorks not on object Assert.AreEqual(4, s.Count); // toString, valueOf, skunkWorks, and bizbuzz (no foobar) Assert.AreEqual("skunky!", s.skunkWorks); // Can access it through string instance previously created Assert.IsFalse(s.foobar); // Feature detection - since prototype was changed, no longer there! }
private static dynamic StringConstructor(this JS js, dynamic value) { dynamic s = new JSObject(); s.JSTypeName = "String"; // Set up the prototype first dynamic p = new JSObject(); s.Prototype = s.GetPrototype(p); // Set up the instance behavior var _primitiveValue = (value == null) ? null : (value is JSObject && JS.cs.Boolean(value.toString as string)) ? value.toString() : value.ToString(); s.toString = s.valueOf = new Func<string>(() => _primitiveValue); return s; }
public virtual dynamic GetPrototype(JSObject defaultValue) { return GetPrototype(JSTypeName, defaultValue); }