Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Different behaviour for fields with default values in field/in constructor #88

Open
micw opened this issue Jul 23, 2015 · 2 comments
Open
Labels
Milestone

Comments

@micw
Copy link

micw commented Jul 23, 2015

When I define a class that has a field with default values, in Java it's the same if the value is set directly to the field or if it's set in the constructor. The generated javascript is different with different behaviour:

public class Data
{
public String str1="String 1";
public String str2;
public Data() {
str2="String 2";
}
}

In javascript "str1" is set in the prototype, "str2" is set in the constructor. The "new Data().str1" and "new Data().str2" both give the same result but JSON.stringify(new Data()) only contains str2.

@npiguet npiguet added the Bug label Jul 23, 2015
@npiguet
Copy link
Member

npiguet commented Jul 24, 2015

This is indeed caused by the fact that we put the default values of instance fields into the prototype of the class. One of the side effect of doing this is that hasOwnProperty() for those fields will return false if the value has not been overwritten.

JSON.stringify() only serializes the own properties of objects, and skips anything that exists only in the prototype.

As a workaround, assign your fields in the constructor until the problem is fixed.

@npiguet npiguet added this to the Version 4 milestone Jul 24, 2015
@npiguet
Copy link
Member

npiguet commented Jul 24, 2015

Moving this to version 4. Fixing this requires a pretty big refactoring of the way class inheritance is done, and of the way instance fields are initialized. On the positive side, if we fix this, we should also be able to remove all the limitations we have currently placed on initializing fields out of the constructor (currently only constants are allowed, IIRC)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants