這個問題已經被提出並且提出的解決方案是使用'bind'。但是如何在這種情況下使用「綁定」?在原型中保留'this'上下文
var Fun = function(){
this.count = 100;
}
Fun.prototype.f = function(){
console.log("in f : " + this.count);
}
Fun.prototype.g = {
f : function(){
console.log("in g-f : " + this.count);
// Is it possible to use 'bind' here to access 'this' of 'Fun'
}
}
fun = new Fun();
fun.f(); // Results - in f : 100
fun.g.f(); // Results - in g-f : undefined
fun.g.f.bind(fun)(); // Results - in f : 100
是否有可能使用bind
在這樣g.f
fun.g.f()
會給結果in f : 100
?
@NEB:這是不可能的,那些是兩個不同的對象。 – zerkms