【问题标题】:Context of 'this' in ES6 [duplicate]ES6中“this”的上下文[重复]
【发布时间】:2016-05-23 06:38:49
【问题描述】:

我刚从 ES5 的背景开始学习 ES6 和 ReactJS。

这段 ES6 代码让我摸不着头脑。

代码#1:

class App extends Component {

    constructor(props) {
       super(props);
       this.state = { videos: [] };

        YTSearch({key: API_KEY, term: 'surfboard'}, function(data) {
            this.setState({ videos: data }); **//I GET AN ERROR HERE!!**
        });
    }

    render() {
        return (
            <div>
                <SearchBar />
            </div>
        );
    }
}

我在this.setState 中得到一个error

bundle.js:19826 TypeError: Cannot read property 'setState' of undefined(…)

但是,如果我这样做了

代码#2:

YTSearch({key: API_KEY, term: 'surfboard'}, (data) => {
    this.setState({ videos: data }); **//I GET AN ERROR HERE!!**
});

这很好用。

我可以理解在第一种情况下,一般function 中的this 的范围在回调(如AJAX)中是不同的。但在示例 #2 中,情况有何变化?

【问题讨论】:

标签: javascript reactjs ecmascript-6


【解决方案1】:

在 ES6 中,当您编写胖箭头 / lamda 函数时,this 上下文被保留(这就是您的第二个示例有效的原因)。

但是在您的第一个示例中,您使用function() {}this 上下文没有保留,因此函数内的“this”不是您所期望的,它是函数的新上下文。

【讨论】:

    【解决方案2】:

    if 绑定使用普通的function 语句设置为callsite,但使用fat arrowscallsite 不是动态设置的。

    话虽这么说;函数 中的this 在您阅读本文后您所期望的。在 JQuery 函数中非常有用,因为通常您可以这样做:

    正则函数

    function hi(){
        var name;
        $('element').on('action', function(){this.name = 'hi'});
    
        //now the name var is undefined;
        //instead, the object (element) has a property called name with 'hi'.
    }
    

    胖箭头

    function hi(){
        var name;
        $('element').on('action', () => this.name = 'hi');
    
        //now the name var is 'hi';
        //the object (element) has no property 'name' now.
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      • 1970-01-01
      • 2021-10-16
      相关资源
      最近更新 更多