class SomeClass {
constructor() {
this.x = 0;
}
getSomething(inputVal) {
let self = this;
return new Promise((resolve, reject) => {
setTimeout(function(){
if(inputVal){
self.x = 1;
resolve();
}
else{
self.x = -1;
reject();
}
}, 10);
});
}
我必须使用一个名为 self
的变量来引用 this
。这是错误的做法吗?如果没有,我还能怎么做?
Is this wrong to do?
不,显然那个方法并没有错,它只是一种保持对this
的引用的方法。目的。
但是对于这个问题还有一些替代方法:
1。使用 bind
方法。
The bind() method creates a new function that, when called, has its
this keyword set to the provided value, with a given sequence of
arguments preceding any provided when the new function is called.
getSomething(inputVal) {
return new Promise((resolve, reject) => {
setTimeout(function(){
if(inputVal){
this.x = 1;
resolve();
}
else{
this.x = -1;
reject();
}
}.bind(this), 10);
});
}
2。使用 arrow
功能。
直到 arrow
函数,每个 new
函数定义了自己的this
值(value)。
例如,this
在构造函数的情况下可以是一个新对象。
function Person(age){
this.age=age;
console.log(this);
}
let person=new Person(22);
或this
可以指向到base
对象,如果创建的函数可以像obj.getAge()
那样被访问.
let obj={
getAge:function(){
console.log(this);
return 22;
}
}
console.log(obj.getAge());
安arrow
函数不创建自己的 this
, 它只是使用了 this
enclosing
的值(value)执行context
.另一方面,arrow
函数使用 this
父范围。
getSomething(inputVal) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (inputVal) {
this.x = 1;
resolve();
}
else {
this.x = -1;
reject();
}
}, 10);
});
}