在javascript中,我应该尽可能使用const代替var吗? [英] In javascript should I use const instead of var whenever possible?

查看:576
本文介绍了在javascript中,我应该尽可能使用const代替var吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果创建对对象的引用,并且引用不会改变(即使对象将),最好使用const而不是var?

If creating a reference to an object, and the reference is not going to change (even though the object will), is it better to use const instead of var?

例如:

const moment = require('moment')

exports.getQuotation = function(value) {

    const quotation = {};
    quotation.value = value;
    quotation.expiryDate = moment().add(7, 'days');

    // Do some other stuff with quotation perhaps

    return quotation;

};


推荐答案

可以使用const,但必须运行节点在 - 和谐

You can use const, but you have to run node on --harmony

node app.js --harmony

您还必须设置use strict否则你会有运行时执行问题:

You also have to set "use strict", otherwise you'll have run-time execution issues:

exports.getQuotation = function(value) {
    "use strict";

    const I_AM_CONSTANT = {};
    let quotation = {};
    ...

除此之外,如果您在<$ c上运行节点$ c> - 和谐,在语义上,对于常量使用 const 更有意义。对于实际变量,您应该使用 let 而不是var,因为 let 仅定义范围中的变量(避免提升问题)

Other than that, yes if you are running node on --harmony, semantically it makes more sense to use const for constants. For actual variables you should use let instead of var, as let only defines the variable in the scope (avoids hoisting issues)

这篇关于在javascript中,我应该尽可能使用const代替var吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆