• source navigation  • diff markup  • identifier search  • freetext search  • 

Sources/ucode/tests/custom/03_stdlib/63_call

  1 The `call()` function allows invoking functions with a modified `this` context
  2 and global environment. It's main use case is binding global variables for
  3 dynamiclly loaded code at runtime.
  4 
  5 Returns `null` if the given function value is not callable.
  6 Returns the value returned by the invoked function in all other cases.
  7 
  8 
  9 Test modifying `this` context
 10 
 11 -- Testcase --
 12 {%
 13         let o1 = {
 14                 name: "Object #1",
 15                 func: function() {
 16                         print(`This is ${this.name}\n`);
 17                 }
 18         };
 19 
 20         let o2 = {
 21                 name: "Object #2"
 22         };
 23 
 24         o1.func();
 25         call(o1.func, o2);
 26 %}
 27 -- End --
 28 
 29 -- Expect stdout --
 30 This is Object #1
 31 This is Object #2
 32 -- End --
 33 
 34 
 35 Test modifying environment
 36 
 37 -- Testcase --
 38 {%
 39         function fn() {
 40                 print("Hello world\n");
 41         }
 42 
 43         fn();
 44         call(fn, null, { print: (s) => printf("Overridden print(): %s", s) });
 45 %}
 46 -- End --
 47 
 48 -- Expect stdout --
 49 Hello world
 50 Overridden print(): Hello world
 51 -- End --
 52 
 53 
 54 Test isolating environment
 55 
 56 -- Testcase --
 57 {%
 58         function fn() {
 59                 print("Hello world\n");
 60         }
 61 
 62         fn();
 63         call(fn, null, proto({}, {})); // should fail due to unavailable print
 64 %}
 65 -- End --
 66 
 67 -- Expect stdout --
 68 Hello world
 69 -- End --
 70 
 71 -- Expect stderr --
 72 Type error: left-hand side is not a function
 73 In fn(), line 3, byte 24:
 74   called from function call ([C])
 75   called from anonymous function ([stdin]:7:30)
 76 
 77  `        print("Hello world\n");`
 78   Near here -------------------^
 79 
 80 
 81 -- End --
 82 
 83 
 84 Test passing through arguments
 85 
 86 -- Testcase --
 87 {%
 88         function fn(a, b) {
 89                 printf("The product of %d * %d is %d\n", a, b, a * b);
 90         }
 91 
 92         fn(3, 4);
 93         call(fn, null, null, 5, 6);
 94         call((...args) => printf("Args: %J\n", args), null, null, 1, 2, 3, 4, 5, 6);
 95 %}
 96 -- End --
 97 
 98 -- Expect stdout --
 99 The product of 3 * 4 is 12
100 The product of 5 * 6 is 30
101 Args: [ 1, 2, 3, 4, 5, 6 ]
102 -- End --

This page was automatically generated by LXR 0.3.1.  •  OpenWrt