Path: blob/aarch64-shenandoah-jdk8u272-b10/nashorn/samples/engine/foreignobject.js
32284 views
#// Usage: jjs -scripting foreignobject.js12/*3* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.4*5* Redistribution and use in source and binary forms, with or without6* modification, are permitted provided that the following conditions7* are met:8*9* - Redistributions of source code must retain the above copyright10* notice, this list of conditions and the following disclaimer.11*12* - Redistributions in binary form must reproduce the above copyright13* notice, this list of conditions and the following disclaimer in the14* documentation and/or other materials provided with the distribution.15*16* - Neither the name of Oracle nor the names of its17* contributors may be used to endorse or promote products derived18* from this software without specific prior written permission.19*20* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS21* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,22* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR23* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR24* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,25* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,26* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR27* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF28* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING29* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS30* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.31*/3233// cross nashorn engine scripting34// access script objects from other engines in natural syntax3536var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");37// create manager38var manager = new ScriptEngineManager();39// create engine40var engine = manager.getEngineByName("js");4142// eval code!43engine.eval(<<CODE44var obj = {45foo: 42,46func: function() {47print("func: " + this.foo);48}49};50CODE);5152// Nashorn engine returns script objects as instance of53// the class jdk.nashorn.api.scripting.ScriptObjectMirror54// But nashorn's dynalink linker can treat these objects55// specially to support natural script syntax to access..56// In Java code, you need to use ScriptObjectMirror's57// methods though. Once again, script world is simpler :-)5859var foreignObj = engine.get("obj");60// access properties, functions of it61// with natural syntax62print(foreignObj.foo);63foreignObj.func();64print(typeof foreignObj.func);6566// access engine's global67var foreignGlobal = engine.eval("this");68// create objects in engine's world from here!69print(new foreignGlobal.Object());70print(new foreignGlobal.Date());717273