2016-10-22 55 views
0

我只想知道这是否可能。我已经使用Javascript四年作为一个Web开发人员,所以我非常习惯在我的代码中使用匿名函数。现在正在测试Processing,我想看看如何通过Javascript来完成所有我通常做的事情。Java处理,使用匿名函数

在Javascript中,我使用的功能,像这样:

fn.call(instance,arg1, arg2); 

fn.apply(instance,args); 

...但是,我不能做这样的事情在处理。

我试图调用一个“匿名函数”,并在实例的命名空间中运行函数:

public void resetHealth(){ 
    this.health = 10; 
} 

class Player{ 
    public int health; 
    Player(){ 
     super(); 
     this.health = 10; 
    } 
} 

Player p = new Player(); 

//where it gets prickly: 

resetHealth.invoke(p); 

预期结果:print p.health; //returns 0

我想知道什么,我Java的做法是错误的。但是,它可能与处理有关。

+1

为什么resetHealth是Player类之外的函数?现在这个方法没有上下文或含义。 –

+0

原因是我可以共享函数并将它们传递给它们,而不是将函数放入类中。有没有办法做到这一点? –

+0

请参阅Java 8 [方法参考](https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html)。但我鼓励你简单地定义[interfaces](https://docs.oracle.com/javase/tutorial/java/concepts/interface.html),并传递实现该接口的对象。 “把方法放在物体内”是好的:) – paulsm4

回答

0

从长远来看,我建议检查出Daniel Shiffman's OOP Tutorial

你应该将你的resetHealth()函数Player类里面, 然后使用称它为点符号(如p.resetHealth()

class Player { 
    public int health; 
    Player() { 
    super(); 
    this.health = 10; 
    } 
    public void resetHealth() { 
    this.health = 10; 
    } 
} 

void setup() { 
    Player p = new Player(); 

    //test, set lower health 
    p.health = 3; 
    println("lowed health to", p.health); 

    //test, call reset health 
    p.resetHealth(); 
    println("reset health to", p.health); 
} 

如果您'已经习惯了JavaScript,你应该在使用p5.js的时候感觉自在,同时仍然使用大部分的加工好东西。

+0

感谢您的快速反应,那就回答了!我想用Java来说,对小而简洁的代码没有太大的需求。我只是利用类继承,我也用Javascript做的。 –

+0

Java是一种编译语言,所以你会发现很多东西比较严格(比如严格类型转换,类结构等),在JavaScript中被解释,所以在动态类型方面有更多的灵活性。如果你想去java,假装你忘了OOP和继承,并开始就像从头开始一样。这可能更容易/更少混淆,因为语言之间存在很多差异。如果你想让大部分的JS知识,我建议使用p5.js。 –