在构造函数中定义对象属性

时间:2018-05-21 11:14:28

标签: javascript object

所以,我想在这个类中添加对象属性(使用Consturctor定义它),但是我收到了一个错误。我做错了什么?有没有其他方法可以做到这一点?

class Currency
{
    Constructor()
    {
        /* Properties */
        this.ticker   = null;
        this.name     = null;

        /* Markets availability */
        this.marketBTC =
        {
            availability: true,
            ask: 0.010,
            bid: 0.009,
            last: 0.010
        };
    }
}

var a = new Currency();

console.log(a.marketBTC.ask); // error: Cannot read property 'ask' of undefined

2 个答案:

答案 0 :(得分:3)

JavaScript区分大小写,它是constructor,而不是Constructor

请参阅the MDN on classes

答案 1 :(得分:1)

Javascript区分大小写,因此将Consturctor更改为consturctor



class Currency
{
    constructor()
    {
        this.ticker   = null;
        this.name     = null;
        this.marketBTC =
        {
            availability: true,
            ask: 0.010,
            bid: 0.009,
            last: 0.010
        };
    }
}

var a = new Currency();

console.log(a.marketBTC.ask);