【问题标题】:When bind is not set, why `this` is not referring to the window object?未设置绑定时,为什么 `this` 不是指窗口对象?
【发布时间】:2017-04-15 19:44:52
【问题描述】:

我想知道为什么如果我将这行{this.increaseQty.bind(this)}修改为{this.increaseQty},控制台会提示Uncaught TypeError: Cannot read property 'setState' of undefined 而不是Uncaught TypeError: this .setState 不是函数(...) ??如果没有设置绑定,this不应该是窗口对象吗?

export default class CartItem extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            qty: props.initialQty,
            total: 0
        };
    }
    componentWillMount() {
        this.recalculateTotal();
    }
    increaseQty() {
        this.setState({qty: this.state.qty + 1}, this.recalculateTotal);
    }
    decreaseQty() {
        let newQty = this.state.qty > 0 ? this.state.qty - 1 : 0;
        this.setState({qty: newQty}, this.recalculateTotal);
    }
    recalculateTotal() {
        this.setState({total: this.state.qty * this.props.price});
    }
    render() {
        return <article className="row large-4">
            <figure className="text-center">
                <p>
                    <img src={this.props.image}/>
                </p>
                <figcaption>
                    <h2>{this.props.title}</h2>
                </figcaption>
            </figure>
            <p className="large-4 column"><strong>Quantity: {this.state.qty}</strong></p>

            <p className="large-4 column">
                <button onClick={this.increaseQty.bind(this)} className="button success">+</button>
                <button onClick={this.decreaseQty.bind(this)} className="button alert">-</button>
            </p>

            <p className="large-4 column"><strong>Price per item:</strong> ${this.props.price}</p>

            <h3 className="large-12 column text-center">
                Total: ${this.state.total}
            </h3>

        </article>;
    }
}

【问题讨论】:

  • 在 ES6 中你默认处于严格模式,所以这将是 undefined

标签: javascript reactjs


【解决方案1】:

如果你不将函数作为方法调用(并且它没有被绑定,并且你没有使用call或apply),那么函数内部this的值将是undefined IF:

  • 您处于严格模式
  • 你在 ES2015 中(默认开启严格模式)

否则它将是全局对象。

另外,请注意,一些宿主对象(例如 setTimeout)有自己的特定行为,用于定义在调用回调时使用的 this 值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-19
    • 2013-12-30
    • 2019-01-22
    • 2017-05-26
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    相关资源
    最近更新 更多