Suppose I have Foo.class in Java:
public class Foo { public int id; public String data; }
And that I have a Foo "class" in JavaScript:
function Foo(id, data) { this.id = id; this.data = data; }
Also suppose I have a Java controller that returns an instance of Foo.class in response to a REST request. In my JavaScript (AngularJS) code, the request is sent as:
$http.get(url + 'bar/get-foo/') .success(function (response) { var foo = new Foo(response.id, response.data); logger.info("SUCCESS: /get-foo"); }) .error(function (error_message) { logger.error(error_message) });
And it works. But is there any way to avoid passing each property from the response to the Foo constructor (some kind of waiting for the Foo object or its inclusion in the Foo object)?
I tried using Object.create(Foo, response) , but I get TypeError: Property description must be an object: true
Of course, there is always the option of refactoring the constructor with JavaScript Foo:
function Foo(foo) { this.id = foo.id; this.data = foo.data; }
But this will require refactoring a large part of the code base.
Thank you for your time. I appreciate it!
PS: For those who wonder why I need it: this is not a problem with small classes like Foo, but some answers are examples of much larger classes (with more than a dozen fields) that are not under my control.
EDIT: I made Chichozell's decision simply because it requires the least amount of work. The Robin and jonnyknowsbest answers also work (and will work in pure JavaScript, unlike the Chichozell answer, which is specific to AngularJS). Did not try Laurentiu L. to answer, but it seems that it should work too. In any case, this is a solution (not a solution):
.success(function (response) { var foo = new Foo(); angular.extend(foo, response);
Many thanks to everyone who replied / commented / edited this topic.