简体   繁体   English

Java对象可以成为Nashorn中JavaScript对象的原型吗?

[英]Can a Java Object be a Prototype of an JavaScript Object in Nashorn?

Is it possible to make an Java object the prototype of a JavaScript object? 是否可以使Java对象成为JavaScript对象的原型? Like the following: 如下:

var Person = Java.type("Person");
var hans = new Person();
hans.name = "Hans";

var employeeFactory = function() {
    var F = function(){};
    F.prototype = hans;
    return new F();
};

var fritz = employeeFactory();
print(fritz.name);

Here Person is a Java Bean. 这里Person是一个Java Bean。 The variable hans is set as the instance of this Java class. 变量hans被设置为此Java类的实例。 The line hans.name = "Hans" sets the name field in the Java object as expected. 行hans.name =“Hans”按预期在Java对象中设置名称字段。 But when the object fritz is created in the factory function, it doesn't get linked to the expected prototype. 但是当在工厂函数中创建对象fritz时,它不会链接到预期的原型。 Is there any reason why the Java instance isn't accepted as prototype? 是否有任何理由不接受Java实例作为原型?

It might work in Rhino, because in Rhino all beans are wrapped into JS native objects before being exposed to the JS program. 它可能在Rhino中有效,因为在Rhino中,所有bean在暴露给JS程序之前都被包装到JS本机对象中。 Nashorn OTOH doesn't create wrappers. Nashorn OTOH不会创建包装器。 You can, however, use Nashorn's non-standard Object.bindProperties that adds properties from one object to another, bound to the original object's instance as its this. 但是,您可以使用Nashorn的非标准Object.bindProperties ,它将属性从一个对象添加到另一个对象,并将其绑定到原始对象的实例。 That's essentially as close as you can get (well, it's pretty darn close) to a wrapper. 这基本上就像你可以得到的那样接近(好吧,它非常接近)一个包装器。 The exact specification is: 确切的规格是:

Object.bindProperties(dst, src)

creates bound properties from all properties in src object, puts them into the dst object, and returns the dst object. src对象中的所有属性创建绑定属性,将它们放入dst对象,并返回dst对象。 Since the properties are bound to src , dst.foo will delegate to src.foo for its value. 由于属性绑定到srcdst.foo将委托给src.foo获取其值。 bindProperties has been coded specifically so that it can handle ordinary Java objects as src . bindProperties已经被专门编码,因此它可以像src一样处理普通的Java对象。

With that in mind, I believe that if you change the line 考虑到这一点,我相信如果你改变了这条线

F.prototype = hans;

to

F.prototype = Object.bindProperties({}, hans);

you'll get what you wanted. 你会得到你想要的。 That would work with Object.create too, eg Object.create(Object.bindProperties({}, somePojo)) . 这也适用于Object.create ,例如Object.create(Object.bindProperties({}, somePojo))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM