[英]Is it possible to simulate Javascript-style prototypes in Java?
I'd like to know whether it's possible to simulate Javascript prototypes in Java. 我想知道是否可以在Java中模拟Javascript原型。 Is it possible to associate a list of variables with a function in Java? 是否可以将变量列表与Java中的函数相关联? I want to create something similar to Javascript prototypes, if that's even possible. 我想创建类似于Javascript原型的东西,如果可能的话。
So here's an example (in Javascript): 所以这是一个例子(在Javascript中):
var s = doStuff.prototype;
s.isImplemented = false;
function doStuff(){
//this function has not yet been implemented
}
var s = functionIsImplemented.prototype;
s.isImplemented = true;
function functionIsImplemented(theFunction){
//this function returns true if the function has been identified as "implemented"
if(theFunction.prototype.isImplemented == true){
return true;
}
return false;
}
alert(functionIsImplemented(doStuff)); //this should print "false"
alert(functionIsImplemented(functionIsImplemented)); //this should print "true"
Is there any way to do the equivalent of this in Java? 有没有办法在Java中完成相同的操作?
Yes, it's certainly possible, and can be very useful for some situations. 是的,它当然是可能的,并且在某些情况下非常有用。
Typically you would do the following: 通常,您会执行以下操作:
It's not as elegant as if you do this directly in a dynamic language, but it works and gets you the same benefits (runtime flexibility, avoid constraints of rigid OOP, fast proptotyping etc.). 它不像在动态语言中直接执行它那样优雅,但它可以工作并获得相同的好处(运行时灵活性,避免严格OOP的约束,快速的proptotyping等)。
It also has the same downsides - loss of static type checking and some performance overhead being the main ones. 它也有相同的缺点 - 静态类型检查的丢失和一些性能开销是主要的。
As an example, the open source game I wrote ( Tyrant ) uses this approach for all the in-game objects. 举个例子,我写的开源游戏( 暴君 )将这种方法用于所有游戏内对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.