She*_*pir 0 javascript ecmascript-6 babeljs
我正在使用Babel和ES2015.并且想this在callback里面使用内部方法.
class baz {
bar = "xxx";
foo() {
x(function() {
console.log(this.bar);
});
}
}
function x(callback) {
return callback();
}
var y = new baz();
y.foo();
Run Code Online (Sandbox Code Playgroud)
https://jsfiddle.net/dnthehnt/7/ 我收到了
TypeError:这是未定义的
因为据我所知,这指的是回调函数x().作为我使用的解决方案
class baz {
bar = "xxx";
foo() {
var bar = this.bar;//<=====
x(function() {
console.log(bar);//<=====
});
}
}
function x(callback) {
return callback();
}
var y = new baz();
y.foo();
Run Code Online (Sandbox Code Playgroud)
https://jsfiddle.net/dnthehnt/6/ 并获得
XXX
这是解决方案,但如果你有大量的代码,它会变得非常混乱和难以编写.有没有更好的解决方案this?或者ES6的任何其他学科使用回调和这个.
查看箭头函数,尤其this是与经典函数相比,箭头函数处理的方式.
class baz {
constructor() { this.bar = "xxx"; }
foo() {
x(() => {
console.log(this.bar);
});
}
}
Run Code Online (Sandbox Code Playgroud)
如果在调用x和调用回调之间更改了bar,则使用经典函数的解决方案将无法工作.
这就是你应该如何使用经典功能
class baz {
constructor() { this.bar = "xxx"; }
foo() {
const self = this;
x(function () {
console.log(self.bar);
});
}
}
Run Code Online (Sandbox Code Playgroud)
或者你可以使用bind,我想.
class baz {
constructor() { this.bar = "xxx"; }
foo() {
x((function () {
console.log(this.bar);
}).bind(this));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2781 次 |
| 最近记录: |