0

In Javascript how would I create a Custom Object that has a property this is another Custom Object. For Example.

function Product() {
    this.prop1 = 1;
    this.prop2 = 2;
}


function Work(values) {
    this.front = values.front || "default";
    this.back = values.back || "default";
    this.product =  Product;
}

var w = new Work();
alert(w.product.prop1); //no worky
0

1 Answer 1

3

You need to create an instance of Product, like this:

function Product() {
    this.prop1 = 1;
    this.prop2 = 2;
}
function Work(values) {
    this.front = values && values.front || "default";
    this.back = values && values.back || "default";
    this.product = new Product();
}
var w = new Work();
alert(w.product.prop1); //1

The front and back changes are a separate issue, since values wasn't being passed in in your example, you'd get an undefined error. You can test the result here.


Here's an alternative way I'd personally use to define those defaults:

function Work(values) {
    values = values || { front: "default", back: "default" };
    this.front = values.front;
    this.back = values.back;
    this.product = new Product();
}

You can try that version here.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I tried that also but it was failing before it got to the alert because of how I was trying to set the front and back properties. Can I ask what "this.front = values && values.front || "default";" does in english?
@TooFat - It's checking that values isn't falsy (undefined in this case) before trying to get a property from it, if it's false it'll immediately go to the OR (||) and grab the default.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.