是否可以在 Java 中模拟 Javascript 风格的原型? [英] Is it possible to simulate Javascript-style prototypes in Java?

查看:46
本文介绍了是否可以在 Java 中模拟 Javascript 风格的原型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在 Java 中模拟 Javascript 原型.是否可以将变量列表与 Java 中的函数相关联?如果可能的话,我想创建类似于 Javascript 原型的东西.

I'd like to know whether it's possible to simulate Javascript prototypes in Java. Is it possible to associate a list of variables with a function in Java? I want to create something similar to Javascript prototypes, if that's even possible.

这里有一个例子(在 Javascript 中):

So here's an example (in 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"​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

有什么办法可以在 Java 中做到这一点吗?

Is there any way to do the equivalent of this in Java?

推荐答案

是的,这当然是可能的,并且在某些情况下非常有用.

Yes, it's certainly possible, and can be very useful for some situations.

通常您会执行以下操作:

Typically you would do the following:

  • 创建一个包含属性映射的类.这将成为您所有原型的基本对象"类.K可能是String,V可能是Object
  • 为您的属性创建 getter 和 setter
  • 可选地添加其他实用方法,例如检查函数是否实现基本上意味着检查属性映射包含特定键
  • 通过克隆另一个对象的属性映射或(更复杂的)保持对原始对象的引用来实现基于原型的继承
  • 使用某种函数对象来允许在属性中存储任意代码

它不像直接在动态语言中那样优雅,但它可以工作并为您带来相同的好处(运行时灵活性、避免刚性 OOP 的约束、快速原型设计等).

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.).

它也有同样的缺点 - 静态类型检查的损失和一些性能开销是主要的.

It also has the same downsides - loss of static type checking and some performance overhead being the main ones.

举个例子,我写的开源游戏(Tyrant)使用这种方法来处理所有的游戏内物品.

As an example, the open source game I wrote (Tyrant) uses this approach for all the in-game objects.

这篇关于是否可以在 Java 中模拟 Javascript 风格的原型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆