简体   繁体   中英

Object-Oriented JavaScript Converter

So I am working in a converter application powered by JavaScript, and right now I am trying to create a huge object with all the measures. But whenever I debug it, it's saying things like:

 Expected ';' and instead saw '.' (var units.length = {};) Expected '.' at column 1, not column 10 (var units.length = {};) Unexpected '.' (var units.length = {};) etc. 

It's been a long time since I coded in JS, so I'm having some confusion with it, would appreciate any help, here's the code:

var units = {};
var units.length = {};
var units.time = {};
var units.mass = {};
var units.temperature = {};

//Starting with Length
units.length.meter = 1;
units.length.meters = 1;

units.length.inch = 0.0254;
units.length.inches = 0.0254;

units.length.foot = 0.3048;
units.length.feet = 0.3048;

units.length.yard = 0.9144;
units.length.yards = 0.9144;

units.length.mile = 1609.344;
units.length.miles = 1609.344;

...

Only use var to declare variables, not to create properties of an existing object:

var units = {};
units.length = {};
units.time = {};
units.mass = {};
units.temperature = {};

//Starting with Length
units.length.meter = 1;
units.length.meters = 1;

units.length.inch = 0.0254;
units.length.inches = 0.0254;

units.length.foot = 0.3048;
units.length.feet = 0.3048;

units.length.yard = 0.9144;
units.length.yards = 0.9144;

units.length.mile = 1609.344;
units.length.miles = 1609.344;

Also consider

var units = {
    length: {
        meter: 1,
        meters: 1,
        inch: 0.0254,
        inches: 0.0254,
        foot: 0.3048,
        feet: 0.3048,
        yard: 0.9144,
        yards: 0.9144,
        mile: 1609.344,
        miles: 1609.344
    },
    time: {},
    mass: {},
    temperature: {}
};

No var before attributes, only variables.

var units = {
    length: {},
    time: {},
    mass: {},
    temperature : {}
};

NB: length is reserved to array/string length, you should avoid to name an attribute like that. And you should use an extend method to avoid to repeat units and units.length .

var units = {
    length: {
        meter: 1,
        meters: 1,
        inch: 0.0254,
        inches: 0.0254 // ...
    },
    time: {},
    mass: {},
    temperature : {}
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM