开发者

How to create an Custom Object with a Custom Object?

In Javascript how would I cre开发者_高级运维ate 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜