【发布时间】:2016-08-21 11:08:34
【问题描述】:
我有一个组件在创建时请求数据。但是,当返回数据时,我无法访问此数据或直接父级范围内的任何内容。
// Service
class DataService {
getDataFromService() {
var p = new Promise(function(resolve, reject) {
resolve({ message: 'hello world' });
});
return p;
}
}
var dataService = new DataService();
// Component
Vue.component('review', {
created: function() {
this.fetchData();
},
methods: {
fetchData: function() {
var that = this;
var hello = 'world';
// normal function
dataService.getDataFromService().then(function(data) {
this.foo = data.message; // 'this' is undefined
that.bar = data.message; // 'that' is undefined
console.log(hello); // 'hello' is undefined
});
// fat arrow
dataService.getDataFromService().then((data) => {
this.foo = data.message; // 'this' is undefined
that.bar = data.message; // 'that' is undefined
console.log(hello); // 'hello' is undefined
});
},
},
});
在上面的示例中,'this' 和 'that' 都未定义,我不知道为什么。我正在使用 babel & browserify 来编译代码。
我尝试将服务更改为使用回调而不是没有改变任何东西的承诺。我还尝试使用普通的“函数(数据)”而不是胖箭头函数。
更新: 该示例适用于JSFiddle!我猜这意味着它与 babel/browserify/modules 有关。
【问题讨论】:
-
如果你不使用函数字面量,你可能会更轻松,因为你可以访问 ES6 语法。
-
我已经尝试过标准和粗箭头功能。两者都没有改变。我已更新问题以包含此信息。
-
this在非箭头函数中的值与that不同可能是可以理解的,但hello未定义意味着您的环境中存在严重错误。 JavaScript 中不允许这种行为。 -
您提供的代码 sn-p 无法完全复制您在 cmets 中列出的输出。变量
hello根本无法记录undefined,因为它在范围内并且没有被任何其他局部变量别名。您提供的小提琴之所以有效,是因为它是正确的(假设 vue 库正确地将fetchData与this绑定)。我猜有两件事你没有理解。函数中this的大小写及箭头与函数表达式的区别。 -
我完全了解范围应该如何工作。是的,它不应该记录未定义,但它是。这就是我发布问题的原因。
标签: javascript promise ecmascript-6 vue.js