Debian Codegraph @

rhino/testsrc/org/mozilla/javascript/tests/DefineFunctionPropertiesTest.java

raw symbols SCIP
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 package org.mozilla.javascript.tests;
6
7 import org.mozilla.javascript.*;
8 import junit.framework.TestCase;
9
10 /**
11 * Example of defining global functions.
12 *
13 * @author Norris Boyd
14 */
15 public class DefineFunctionPropertiesTest extends TestCase {
16 ScriptableObject global;
17 static Object key = "DefineFunctionPropertiesTest";
18
19 /**
20 * Demonstrates how to create global functions in JavaScript
21 * from static methods defined in Java.
22 */
23 @Override
24 public void setUp() {
25 Context cx = Context.enter();
26 try {
27 global = cx.initStandardObjects();
28 String[] names = { "f", "g" };
29 global.defineFunctionProperties(names,
30 DefineFunctionPropertiesTest.class,
31 ScriptableObject.DONTENUM);
32 } finally {
33 Context.exit();
34 }
35 }
36
37 /**
38 * Simple global function that doubles its input.
39 */
40 public static int f(int a) {
41 return a * 2;
42 }
43
44 /**
45 * Simple test: call 'f' defined above
46 */
47 public void testSimpleFunction() {
48 Context cx = Context.enter();
49 try {
50 Object result = cx.evaluateString(global, "f(7) + 1",
51 "test source", 1, null);
52 assertEquals(15.0, result);
53 } finally {
54 Context.exit();
55 }
56 }
57
58 /**
59 * More complicated example: this form of call allows variable
60 * argument lists, and allows access to the 'this' object. For
61 * a global function, the 'this' object is the global object.
62 * In this case we look up a value that we associated with the global
63 * object using {@link ScriptableObject#getAssociatedValue(Object)}.
64 */
65 public static Object g(Context cx, Scriptable thisObj, Object[] args,
66 Function funObj)
67 {
68 Object arg = args.length > 0 ? args[0] : Undefined.instance;
69 Object privateValue = Undefined.instance;
70 if (thisObj instanceof ScriptableObject) {
71 privateValue =
72 ((ScriptableObject) thisObj).getAssociatedValue(key);
73 }
74 return arg.toString() + privateValue;
75 }
76
77 /**
78 * Associate a value with the global scope and call function 'g'
79 * defined above.
80 */
81 public void testPrivateData() {
82 Context cx = Context.enter();
83 try {
84 global.associateValue(key, "bar");
85 Object result = cx.evaluateString(global, "g('foo');",
86 "test source", 1, null);
87 assertEquals("foobar", result);
88 } finally {
89 Context.exit();
90 }
91 }
92 }