我使用此表单来隐藏班级的私人功能:
但是this
总是不符合我的期望。
function Person(){}
Person.prototype = (function(){
console.log(this); // --> window, always
function privateFunc(from){
// private func always loses 'this' even if publicFunc had it
console.log('private', from, this);
}
function publicFunc(from){
// publicFunc has this only when called directly, not by timeout
console.log('public', from, this);
privateFunc(from);
}
return {
PublicFunc: publicFunc
};
})/*.bind(???).*/();
var man = new Person();
man.PublicFunc('direct');
window.setTimeout(man.PublicFunc, 1, 'timeout');
我可以通过手动绑定函数来解决它:
privateFunc.call(this, from);
window.setTimeout(man.PublicFunc.bind(man), 1, 'timeout');
但我不喜欢通过电话呼叫每个私人功能。还有另一种方法吗?