[英]How to create an Custom Object with a Custom Object?
In Javascript how would I create a Custom Object that has a property this is another Custom Object. 在Javascript中,我将如何创建具有属性的自定义对象,这是另一个自定义对象。 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: 您需要创建
Product
的实例,如下所示:
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. front
和back
变化是一个单独的问题,因为在示例中未传递values
,因此会出现undefined
错误。 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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.