Javascript 箭头功能在浏览器中不起作用
下面的方法很好Javascript 箭头功能在浏览器中不起作用,javascript,node.js,reactjs,ecmascript-6,Javascript,Node.js,Reactjs,Ecmascript 6,下面的方法很好 var DBBox = React.createClass({ loadArticlesFromServer: function() { $.ajax({ url: this.props.url, dataType: 'json', data: {username:data.username,isPublished:data.isPublished, heading:data.heading}, cache: false, succ
var DBBox = React.createClass({
loadArticlesFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
data: {username:data.username,isPublished:data.isPublished, heading:data.heading},
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
但如果我在第2行将方法声明更改为箭头函数,如下所示
loadArticlesFromServer: ()=> { //error - Cannot read property 'props' of undefined at line 6
或
我是否错误地使用了箭头功能或遗漏了什么?还是不支持?我正在使用chrome并尝试在没有任何运气的情况下启用harmony flag。箭头函数表达式最适合非方法函数。让我们看看当我们尝试使用它们作为方法时会发生什么
'use strict';
var obj = {
i: 10,
b: () => console.log(this.i, this),
c: function() {
console.log( this.i, this)
}
}
obj.b(); // prints undefined, Window
obj.c(); // prints 10, Object {...}
您应该研究箭头函数中
this
的行为。你不能使用带箭头的bind
。请看(没有双关语)谢谢@Redu,为我指明了正确的方向。
'use strict';
var obj = {
i: 10,
b: () => console.log(this.i, this),
c: function() {
console.log( this.i, this)
}
}
obj.b(); // prints undefined, Window
obj.c(); // prints 10, Object {...}