在下面的代码中,当gs
对象上调用this
时,this
绑定的是什么?我的理解是.
绑定到点(GreetingService
)运算符左侧的东西,在这种情况下应该是gs
对象this.name
。但是,在这种情况下,sayAsyncHi
fn中的undefined
会出现在// file greeting_service.js
function GreetingService(name) {
this.name = name;
this.sayHi = function () {
console.log(this);
console.log(`Hi ${this.name}!`);
}
this.sayAsyncHi = function () {
setTimeout(function (params) {
console.log(this);
console.log(`Hi ${this.name}!`);
},2000);
}
this.sayBye = function () {
console.log(`Bye ${this.name}!`);
}
}
var gs = new GreetingService('Jon');
gs.sayHi(); // Hello Jon!
gs.sayAsyncHi(); // Hello undefined!
中 - 为什么会这样?
node greeting_service.js
运行GreetingService {
name: 'Jon',
sayHi: [Function],
sayAsyncHi: [Function],
sayBye: [Function] }
Hi Jon!
Timeout {
_called: true,
_idleTimeout: 2000,
_idlePrev: null,
_idleNext: null,
_idleStart: 389,
_onTimeout: [Function],
_repeat: null }
Hi undefined!
(nodejs 6)
$scope.GetAllSnimateljiBaseInfo = function () {
$http.get(serviceBase + "GetAllSnimateljiBaseInfo", { timeout: 6000 })
.success(function (response) {
$scope.snimatelji = response;
$scope.snimatelji.splice(0, 0, { "IDsnimatelj": 0, "Ime": "", "Prezime": "" });
$scope.selectedSnimateljInfilterVideoKlip = $scope.snimatelji[0];
})
.error(function (response, status) {
if (status == 401) {
$state.go('/');
}
else {
alert(response.Message);
}
});
};
PS:使用ES6箭头功能,绑定正确,正如上述异步调用所期望的那样
答案 0 :(得分:1)
一个小修补程序(我添加了.bind(this)
):
this.sayAsyncHi = function () {
setTimeout(function (params) {
console.log(this);
console.log(`Hi ${this.name}!`);
}.bind(this), 2000);
}
修改强>
一点解释:在sayAsyncHi
中,您会发现this
变量具有您期望的值。但是传递给setTimeout
的函数没有绑定到this
的任何值。如果需要特定值,则需要显式绑定它。