【问题标题】:what is javascript const class?什么是 javascript 常量类?
【发布时间】:2015-11-19 22:04:32
【问题描述】:

我正在从http://teropa.info/blog/2015/09/10/full-stack-redux-tutorial.html 学习 Redux&React。

在代码sn-ps中:

import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import {connect} from 'react-redux';
import Winner from './Winner';
import Vote from './Vote';

export const Voting = React.createClass({
  mixins: [PureRenderMixin],
  render: function() {
    return <div>
      {this.props.winner ?
        <Winner ref="winner" winner={this.props.winner} /> :
        <Vote {...this.props} />}
    </div>;
  }
});

function mapStateToProps(state) {
  return {
    pair: state.getIn(['vote', 'pair']),
    winner: state.get('winner')
  };
}

export const VotingContainer = connect(mapStateToProps)(Voting);

作者正在从“纯”组件创建“有线”反应组件。我对代码中显示的两个“const”关键词有点困惑。我可以理解 javascript 中的 const 值和对象,但是从 OO 的角度来看,const 类对我来说没有意义。

如果我从第一种和/或第二种情况中删除“const”关键字会有什么不同吗?

【问题讨论】:

    标签: javascript reactjs redux


    【解决方案1】:

    Const 是一个块范围的赋值,它分配一个常量引用(不是常量值)。这意味着您以后不能在该模块中意外地重新分配 Voting 或 VotingContainer。

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

    (是的,你可以用 let/var 切换出 const)

    【讨论】:

    • 我只想指出 const 的行为在严格模式和普通 javascript 之间是不一致的。只有在使用执行环境指令“use strict”时才应该选择使用 const,因为在 Chrome 上,至少 const 在不处于严格模式时会违反块范围。这可以随时更改,导致突然出现未检测到的错误,
    • @Blindman67 那么这是否意味着行为非常不可预测,尤其是如果我希望它在不同的浏览器中运行?是否会简单地删除“const”并仔细解决问题?
    • 如果你正确使用它应该没问题,在严格模式下这些错误会抛出,而在普通的javascript中它们会默默地失败,允许一个错误存在而没有检测到,直到浏览器改变规则..与其不使用 const,不如使用 "use strict" 指令确保所有代码都在严格模式下运行。严格模式的好处是巨大的、更好的语法错误检测、更快的代码以及您的环境不会突然改变的安心。真的,如果你不使用“use strict”,你就是在玩火。
    • 本示例假设您使用的是 ES6 转译器。它有 ES6 模块。 Babel 会将const 变成var
    猜你喜欢
    • 2016-02-13
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    • 2023-04-02
    • 2016-10-19
    • 1970-01-01
    相关资源
    最近更新 更多