一、场景复现
window10 jdk1.8u221
package main;import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import netscape.javascript.JSObject;import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;public class Main extends Application {@Overridepublic void start(final Stage stage) throws IOException {Button button = new Button("弹窗");button.setOnAction(event -> {try {this.createOtherStage();} catch (MalformedURLException e) {e.printStackTrace();}});StackPane stackPane = new StackPane();stackPane.getChildren().add(button);Scene scene = new Scene(stackPane,600,400);scene.setRoot(stackPane);stage.setScene(scene);stage.show();}A apps = new A();public void createOtherStage() throws MalformedURLException {Stage stage = new Stage();final WebView browser = new WebView();final WebEngine webEngine = browser.getEngine();StackPane stackPane = new StackPane();stackPane.getChildren().add(browser);Scene scene = new Scene(stackPane,600,400);String url = new File("./filePage.html").toURI().toURL().toString();webEngine.load(url);webEngine.getLoadWorker().stateProperty().addListener((ObservableValue<? extends Worker.State> ov, Worker.State oldState,Worker.State newState) -> {if (newState == Worker.State.SUCCEEDED) {JSObject win= (JSObject) webEngine.executeScript("window");win.setMember("apps",new A());//(1)//win.setMember("apps",apps);//(2)}});//browser.setContextMenuEnabled(false);scene.setRoot(stackPane);stage.setScene(scene);stage.show();}public static void main(String[] args) {launch(args);}public static class A{@Overridepublic String toString() {return "A{}";}}
}
filePage.html
<html>
<head><meta charset="UTF-8">
</head>
<body>
<div class="top"><button onclick="show()">查看</button><div id="info"></div>
</div>
</body>
<script>var apps = 'test';function show() {document.write("" + apps);}
</script>
</html>
A、运行输出:
undefined
期待输出:
A{}
B、注释掉(1)的代码输出:
test
C、注释掉(1)的代码,打开(2)的代码输出:
A{}
二、分析原因
apps没有被赋值,输出的是test而不是undefined。apps被赋值new A()输出的却是undefined。apps被赋值apps变量时输出的是A{}。可以得出结论就是GC把对象回收了。