ES6 和 promise 中的变量范围 [英] ES6 and variable scope inside a promise
问题描述
不确定我在这里遗漏了什么.
Not sure what I'm missing here.
我需要将data
的输出放入this.contact
.现在,我正在使用静态类变量,但必须这样做似乎很脏.
I need to get the output of data
into this.contact
. Right now, I'm using a static class variable, but it seems dirty to have to do that.
export class contactEdit {
static t; // static class var
constructor() {
this.id = null;
this.contact = null;
contactEdit.t = this;
}
activate(id) {
this.id = id;
let contact = this.contact; // scoped version of class var
return dpd.contacts.get(id).then(function(data) {
console.log(data);
contactEdit.t.contact = data; // this works
contact = data; // this doesn't
});
}
}
通常我会在 activate()
函数内创建一个 var contact
(它在 Chrome 控制台中工作),但这似乎在 ES6 中不起作用.
Normally I would create a var contact
inside the activate()
function (it works in the Chrome console) but this doesn't seem to working in ES6.
Chrome 控制台:
Chrome console:
var c = null;
undefined
c;
null
dpd.contacts.get('a415fdc8f5a7184d').then(function(data) {
c = data;
});
Object {}fail: (n)then: (e,t)__proto__: Object
c;
Object {firstName: "John", lastName: "Doe", id: "a415fdc8f5a7184d"}
推荐答案
您需要做两件事.首先使用箭头函数,其次使用`this.contact = data;
You need to do two things. First, use an arrow function, and second, use `this.contact = data;
activate(id) {
this.id = id;
return dpd.contacts.get(id).then(data => {
console.log(data);
this.contact = data;
});
}
您使用箭头函数是因为它处理 JavaScript 的this
"问题,其中 this 指的是函数的词法范围,而不是您当前所在的对象.使用箭头函数确保箭头函数外的 this
与箭头函数内的 this
相同.
You use an arrow function because it deals with JavaScript's "this
" issue, where this refers to the lexical scope of the function, and not the object you're currently in. Using an arrow function makes sure that this
outside the arrow function is the same as this
inside the arrow function.
您需要使用 this.contact
因为 contact
是类的实例属性.
You need to use this.contact
because contact
is an instance property of the class.
这篇关于ES6 和 promise 中的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!