Rai*_*ain 3 javascript this node.js
鉴于:
var q = {};
q.id = 1234;
q.bonus = {
'a':{
'b':(function(){
//i want to access q.id
var id = this. ??? .id
}),
}
};
Run Code Online (Sandbox Code Playgroud)
应该是什么??? 访问q.id.
要q.id在函数中访问,请b使用Function.prototype.bind
var q = {};
q.id = 1234;
q.bonus = {
'a':{
'b': (function(){
//i want to access q.id
var id = this.id;
console.log(id);
}).bind(q),
}
};
q.bonus.a.b();
Run Code Online (Sandbox Code Playgroud)
您还可以使用Function.prototype.call来更改上下文this
q.bonus.a.b.call(q);
Run Code Online (Sandbox Code Playgroud)