如何在对象内创建 JavaScript 对象?

发布于 2024-11-08 13:50:39 字数 321 浏览 0 评论 0原文

例如:

function userObject(start_value) {  
    this.name = start_value;
    this.address = start_value;
    this.cars = function() {
        this.value = start_value;
        this.count = start_value;
    };
}

显然上述内容不起作用,但希望了解如何让汽车可用: userObject.cars.value = 100000;

干杯!

For example:

function userObject(start_value) {  
    this.name = start_value;
    this.address = start_value;
    this.cars = function() {
        this.value = start_value;
        this.count = start_value;
    };
}

Obviously the above dosent work but would appreciate the direction to take to have cars available as:
userObject.cars.value = 100000;

Cheers!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

゛时过境迁 2024-11-15 13:50:39

请记住,函数(以及“对象定义”)可以嵌套(绝对不要求嵌套,但将其嵌套在此处允许对 start_value 进行闭包):

function userObject(start_value) {  
    this.name = start_value;
    this.address = start_value;
    function subObject () {
        this.value = start_value;
        this.count = start_value;
    }
    this.cars = new subObject();
}

但是,我可能会选择为此(只需创建一个新的“普通”对象):

function userObject(start_value) {  
    this.name = start_value;
    this.address = start_value;
    this.cars = {
        value: start_value,
        count: start_value
    };
}

快乐编码。

Remember that functions (and thus "object definitions") can be nested (there is absolutely no requirement that this is nested, but having it nested here allows a closure over start_value):

function userObject(start_value) {  
    this.name = start_value;
    this.address = start_value;
    function subObject () {
        this.value = start_value;
        this.count = start_value;
    }
    this.cars = new subObject();
}

However, I would likely opt for this (just create a new "plain" Object):

function userObject(start_value) {  
    this.name = start_value;
    this.address = start_value;
    this.cars = {
        value: start_value,
        count: start_value
    };
}

Happy coding.

流星番茄 2024-11-15 13:50:39

如此简单的 anser 就是使用对象语法

function userObject(start_value) {  
 this.name = start_value;
 this.address = start_value;
 this.cars = {
  value: start_value,
  count: start_value
 };
}

so simple anser is to use the object syntax

function userObject(start_value) {  
 this.name = start_value;
 this.address = start_value;
 this.cars = {
  value: start_value,
  count: start_value
 };
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文