取决于
你想继承。我发现如果我使用JavaScript原型来定义对象,那么我只能得到Java对象的静态方法:
function test() {
this.hello = function() {
for(var i in this) {
println(i);
}
};
}
test.prototype= com.acme.app.TestClass; // use your class with static methods
// see the inheritance in action:
var testInstance=new test();
test.hello();
但是,JavaScript也允许对对象实例进行原型分配,因此可以使用这样的函数,并获得更类似Java的继承行为:
function test(baseInstance) {
var obj = new function() {
this.hello=function() {
for(var i in this) {
println(i);
}
};
};
obj.prototype=baseInstance; // inherit from baseInstance.
}
// see the thing in action:
var testInstance=test(new com.acme.TestClass()); // provide your base type
testInstance.hello();
或者使用一个函数(例如。
init
)类似于对象本身的上述函数:
function test() {
this.init=function(baseInstance) {
this.prototype=baseInstance;
};
this.hello=function() {
for(var i in this) {
println(i);
}
};
}
var testInstance=new test();
println(typeof(testInstance.prototype)); // is null or undefined
testInstance.init(new com.acme.TestClass()); // inherit from base object
// see it in action:
println(typeof(testInstance.prototype)); // is now com.acme.TestClass
testInstance.hello();